如何为某些类或ID导入CSS?

时间:2015-04-05 10:41:54

标签: javascript html css

说,我有这个HTML结构:

<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的样式)?

1 个答案:

答案 0 :(得分: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/