是否可以使用 JavaScript 更改 CSS 样式表?(不是对象的样式,而是样式表本身)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6620393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:30:09  来源:igfitidea点击:

Is it possible to alter a CSS stylesheet using JavaScript? (NOT the style of an object, but the stylesheet itself)

javascripthtmlcssstylesheetalter

提问by anonymous-one

Is it possible to alter a CSS stylesheet using JavaScript?

是否可以使用 JavaScript 更改 CSS 样式表?

I am NOTtalking about:

不是在谈论:

document.getElementById('id').style._____='.....';

I AMtalking about altering:

AM谈论改变:

#id {
    param: value;
}

besides doing something dirty (which we haven't tried yet btw), like creating a new object in the head, innerHTML a style tag in there, etc. Although this, even if it did work, would pose a few issues as the style block is already defined elsewhere, and I'm not sure when/if the browser would even parse a dynamically created style block?

除了做一些肮脏的事情(顺便说一句,我们还没有尝试过),比如在头部创建一个新对象,innerHTML 一个样式标签,等等。尽管这样做,即使它确实有效,也会带来一些问题作为样式块已在别处定义,我不确定浏览器何时/是否甚至会解析动态创建的样式块?

回答by Mathieu Rodic

As of 2011

截至 2011 年

Yes you can, but you will be facing cross-browser compatibility issues:

是的,您可以,但您将面临跨浏览器兼容性问题:

http://www.quirksmode.org/dom/changess.html

http://www.quirksmode.org/dom/changess.html

As of 2016

截至 2016 年

Browser support has improved a lot (every browser is supported, including IE9+).

浏览器支持有了很大改进(支持所有浏览器,包括 IE9+)。

  • The insertRule()method allows dynamic addition of rules to a stylesheet.

  • With deleteRule(), you can remove existing rules from a stylesheet.

  • Rules within a stylesheet can be accessed via the cssRulesattributes of a stylesheet.

  • insertRule()方法允许向样式表动态添加规则。

  • 使用deleteRule(),您可以从样式表中删除现有规则。

  • 可以通过cssRules样式表的属性访问样式表中的规则。

回答by Zach Saucier

We can use a combination of .insertRuleand .cssRulesto be able to do this all the way back to IE9:

我们可以使用的组合.insertRule,并.cssRules能够做到这一切的回到IE9方式:

function changeStylesheetRule(stylesheet, selector, property, value) {
    // Make the strings lowercase
    selector = selector.toLowerCase();
    property = property.toLowerCase();
    value = value.toLowerCase();

    // Change it if it exists
    for(var i = 0; i < s.cssRules.length; i++) {
        var rule = s.cssRules[i];
        if(rule.selectorText === selector) {
            rule.style[property] = value;
            return;
        }
    }

    // Add it if it does not
    stylesheet.insertRule(selector + " { " + property + ": " + value + "; }", 0);
}

// Used like so:
changeStylesheetRule(s, "body", "color", "rebeccapurple");

Demo

演示

回答by jfriend00

When I want to programmatically add a bunch of styles to an object, I find it easier to programmatically add a class to the object (such class has styles asscociated with it in your CSS). You can control the precedence order in your CSS so the new styles from the new class can override things you had previously. This is generally much easier than modifying a stylesheet directly and works perfectly cross-browser.

当我想以编程方式向对象添加一堆样式时,我发现以编程方式向对象添加类更容易(此类类在您的 CSS 中具有与其相关的样式)。您可以控制 CSS 中的优先顺序,以便来自新类的新样式可以覆盖您以前拥有的样式。这通常比直接修改样式表容易得多,并且可以完美地跨浏览器工作。

回答by pedro casas

change a property in a style rule

更改样式规则中的属性

function change_css_style (titulo,selector,propiedad,valor) {        
        let i=0;
        while (i<document.styleSheets.length) {
            if (document.styleSheets[i].title==titulo) {
                let y=0;
                while (y<document.styleSheets[i].cssRules.length) {
                    if (document.styleSheets[i].cssRules[y].selectorText==selector) {                                               
                        document.styleSheets[i].cssRules[y].style[propiedad] = valor;                                                                       
                        y = document.styleSheets[i].cssRules.length;
                    } 
                    y++;
                }               
                i=document.styleSheets.length;
            } 
            i++;
        }

    }

DEMO

演示

<style title="chat_inicio">
    .contenido .mensajes {
          width: 100px;
          height: 300px;    
    }
</style>

change the style book with the title chat_iniciowith the selector .contenido .mensajesthe property of the style widthto 475px

转变作风书标题chat_inicio与选择.contenido .mensajes风格的财产宽度475px

<script>
     cambiar_css_style ('chat_inicio','.contenido .mensajes','width','475px');
</script>