Dynamically change CSS rules in JavaScript or jQuery

后端 未结 3 1711
一个人的身影
一个人的身影 2021-02-18 13:21

I\'m looking for a way to change the CSS rules of my stylesheet imported in the document. So I have an external stylesheet and some class and div attri

3条回答
  •  轮回少年
    2021-02-18 14:08

    If you want to add a rule, instead of editing each element's style directly, you can use CSSStyleSheet.insertRule(). It takes two parameters: the rule as a string, and where to insert the rule.

    Example from the above link:

    // push a new rule onto the top of my stylesheet
    myStyle.insertRule("#blanc { color: white }", 0);
    

    In this case, myStyle is the .sheet member of a style element.

    As far as I can tell, the style element must be inserted into the document before you can grab its sheet, and it can't be an external sheet. You can also grab a sheet from document.styleSheets, e.g.

    var myStyle = document.styleSheets[1]; // Must not be a linked sheet.
    myStyle.insertRule("#blanc { color: white }", 0);
    

    Note: The page recommends modifying elements by changing their classes, instead of modifying the rules.

提交回复
热议问题