2015-04-05 22 views
3

說,我有這樣的HTML結構:如何僅爲某些類或ID導入CSS?

<div id="header">Header</div> 
<div id="body">Body</div> 
<div id="footer">Footer</div> 

和外部CSS文件(/styles.css),其中包含

#header{ 
    color:red; 
}  
#footer{ 
    color:red; 
} 

現在用JavaScript的幫助下,我可以很容易地加載整個CSS,所以因爲#header#footer的文字顏色變爲紅色。

使用javascript,是否有可能只加載引用#header的樣式,並在我的樣式表中過濾出任何其他樣式(在我的情況下樣式爲#footer)?

+0

你的意思是刪除它們的瀏覽器性能或服務器優化的緣故?無論哪種方式都有待處理,差異是無法完成的。 – 2015-04-05 10:46:18

+0

@Bryan不,我只是不希望這個樣式表適用於除#header之外的任何東西。 – nicael 2015-04-05 10:47:03

回答

1

這可以通過直接修改應用於當前文檔的CSS規則來完成。

<script type="text/javascript"> 
    // Important: Place this where it will be executed once all the CSS resources have been loaded (i.e, beginning or the end of the body tag) 

    // The will be an array of all the selectors to keep CSS rules for 
    ruleList = ["#header"]; 
    var docRulesEntry = document.all ? 'rules' : 'cssRules'; 

    // Loop through loaded stylesheets 
    for(var i = 0; i < document.styleSheets.length; i++) 
    { 
     if(document.styleSheets[i][docRulesEntry] !== null && document.styleSheets[i][docRulesEntry] !== undefined) 
     { 
      // Loop through stylesheet rules 
      for(var o = 0; o < document.styleSheets[i][docRulesEntry].length; o++) 
      { 
       if(document.styleSheets[i][docRulesEntry][o] !== null && document.styleSheets[i][docRulesEntry][o] !== undefined) 
       { 
        // Check if selector exists in our ruleList array 
        if(ruleList.indexOf(document.styleSheets[i][docRulesEntry][o].selectorText) == -1 
         && document.styleSheets[i][docRulesEntry][o].style !== undefined && document.styleSheets[i][docRulesEntry][o].style !== null) 
        { 
         // Selector was not found, remove CSS rules 
         document.styleSheets[i][docRulesEntry][o].style.cssText = ''; 
        } 
       } 
      } 
     } 
    } 
</script> 

的jsfiddle演示(在Chrome測試):https://jsfiddle.net/ud5svdky/1/

+1

Ohwait ...我不知道現在還在做什麼,但它似乎工作:D – nicael 2015-04-05 11:36:05

+0

@nicael很高興聽到這一點。一般而言,CSS規則修改有點複雜。 – 2015-04-05 11:39:08

+0

我會在現實生活中測試:) – nicael 2015-04-05 11:40:02