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

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

最佳答案

这可以通过直接修改应用于当前文档的 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/

关于javascript - 如何仅为某些类或 ID 导入 CSS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29456440/

相关文章:

html - 菜单中间倒 Angular

html - 如何使带 Angular 表的 2 列

css - "img"中 "a"的中间垂直对齐

javascript - 使用 YUI 3.3 获取节点 ID

javascript - 获取 RangeError : using angular. js 和 php

javascript - 用于实例化单个对象,同时保持可测试性的模式

html - 如何在水平居中元素的左侧或右侧 float 元素?

javascript - 如何获取当前悬停的 anchor 的标题属性?

css - Foundation 5 - 固定位置 div 从网格中弹出

javascript - Angular Material 按钮高度