2012-01-30 55 views
1

我正在修改一箇舊網站,並且專注於使Javascript/jQuery儘可能不顯眼。我正在尋找關於該項目的一部分的一些建議:UJ要求,如果在瀏覽器中關閉Javascript,則所有網站內容仍可供用戶使用。我的網站的一部分有一大堆項目。列表中的每個項目都有自己的描述,它使用CSS display:none默認情況下隱藏它。點擊該項目可以使用jQuery .toggle()來切換描述的可見性,因此無法使用Javascript(無論出於何種原因)的人永遠不會看到它。如果我使用Javascript/jQuery而不是CSS來隱藏描述,那麼當頁面加載時它們都會立即可見,這是我想要避免的。那麼最好的解決方案是什麼?實現不顯眼的Javascript

+0

向我們展示一下列表中的代碼... – Teemu 2012-01-30 11:07:36

回答

3

基本上你可以在你的html元素插入類「無JS」,像這樣

<html class="no-js" lang="en"> 

,如果JavaScript是在客戶端上啓用你很快就會刪除類(使用modernizr或簡單的代碼片段像

<head> 
    <script> 
    (function(d) { 
     d.className = d.className.replace(/(^|\b)no-js(\b|$)/, 'js'); 
    }(document.documentElement)); 
    </script> 
    ... 
</head> 
這樣

可以避開FOUC (flash of unstyled content)只需使用.no-js.js類,像這樣的CSS規則:

.yourlistitems { 
    display: block; 
} 
.js .yourlistitems { 
    display: none; 
} 

這種方法也被H5BP
需要注意的是,你並不真的需要預先.no-js類每一個規則:思維「漸進增強」和術語「非侵入式JavaScript」,您將編碼和風格第一對於也可以在沒有javascript的情況下工作的頁面,那麼您將添加功能(和樣式特異性,前面加上.js類)

+0

謝謝 - 完美的作品。你能解釋一下函數中的/(^ | \ b)和(\ b | $)/究竟是做什麼的? – 2012-01-30 12:17:41

+0

正則表達式查找不屬於另一個類的確切類「no-js」作爲子字符串(如xxxno-js或no-jsxxxx) – fcalderan 2012-01-30 12:22:26

1

您是否想過使用Modernizr實現的方法?

通過腳本將CSS類添加到HTML標記中,該腳本會導致不同的CSS選擇器匹配。

<html> 
<head> 
    <!-- 
    Putting this script in the head adds the "js" 
    class to the html element before the page loads. 
    --> 
    <script type="text/javascript" language="javascript"> 
     document.documentElement.className = "js"; 
    </script> 
    <style type="text/css"> 
     /* 
     Only apply the hidden style to elements within the HTML element 
     that has the js class 
     */ 
     .js .description {display:none;} 
    </style> 
</head> 
<body> 
    <span class="description">Example</span> 
</body> 
</html> 
0

不能告訴我們,如果這真的幫助,因爲潛在的異步操作,但你可以添加一個<script>其預先考慮您的<style> with display: (block|inline|whatever)在您使用純JS,不是jQuery的切換所有相關的顯示器none !important

所以在JS的情況下,CSS顯示設置將被預先覆蓋。

相關問題