【问题标题】:Getting and changing CSS attributes with javascript without looking at a particular element在不查看特定元素的情况下使用 javascript 获取和更改 CSS 属性
【发布时间】:2014-12-14 08:21:46
【问题描述】:

我正在寻找一种无需查看特定元素即可使用 js 获取页面 css 的方法,然后更改 CSS 规则而不是不同元素的 CSS。

例如,假设我想将所有具有蓝色背景的元素的背景颜色更改为红色,然后可能会创建一些新元素。我想找到所有带有蓝色 bg 的 css 类并将它们更改为红色。 document.styleSheets 似乎不太好用:

对于这个页面,我在控制台中尝试了这个。它不记录任何内容。

var logAttr = function(classes){
    if(classes !== null){
        for(var i = 0; i < classes.length; i++) {
            for(var attr in classes[i].style){
                console.log(attr);
            }
        }
    }
};

for(var sheets_idx = 0; sheets_idx < document.styleSheets.length; sheets_idx++){
    logAttr(document.styleSheets[sheets_idx].rules);
    logAttr(document.styleSheets[sheets_idx].cssRules);
}

document.styleSheets[0].rulesdocument.styleSheets[0].document.styleSheets 为空...

【问题讨论】:

  • 为什么document.styleSheets 似乎没有那么好用?你尝试了什么?

标签: javascript css


【解决方案1】:

我确信样式表运行良好,可能您只是没有设法让您的示例运行:看看this

var sheet = (function() {
    // Create the <style> tag
    var style = document.createElement("style");

    // Add a media (and/or media query) here if you'd like!
    // style.setAttribute("media", "screen")
    // style.setAttribute("media", "only screen and (max-width : 1024px)")

    // WebKit hack :(
    style.appendChild(document.createTextNode(""));

    // Add the <style> element to the page
    document.head.appendChild(style);

    return style.sheet;
})();

这将为您创建一个样式表,其中包含所有正确的工作条件。 现在,要以字符串形式插入规则,您只需使用这个东西:

sheet.insertRule('div {position: absolute; top:0px; width:10vh; height:10vw;}')

如果您只想将规则添加到现有规则集:

sheet.addRule('div', 'background-color: red');

如果您想使用自定义函数来执行此操作,只需使用某些参数调用 sheet.addRule:

function add(query, property){

    //don't forget that you need to have already created the sheet!
    sheet.addRule(query, property);
}

查询可以是通过 css 访问的任何内容:.class, #id, h1, #id &gt; h1 &gt; .class

【讨论】:

  • 感谢您对如何更改 CSS 规则的明确回答!似乎document.styleSheets 不起作用的原因在这里讨论link
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 2015-06-29
  • 1970-01-01
  • 2014-06-09
  • 2020-09-18
  • 1970-01-01
相关资源
最近更新 更多