get document.styleSheets by name instead of index?

后端 未结 5 1654
鱼传尺愫
鱼传尺愫 2020-12-25 11:20

document.styleSheets is used with an index,
but what If I want to use stylesheet.insertRule with a specific CSS file ?

I know the file\'s name, which is

5条回答
  •  温柔的废话
    2020-12-25 11:49

    Here is a minor adjustment to the answer by vsync.

    function addRule(stylesheetId, selector, rule) {
      var stylesheet = document.getElementById(stylesheetId);
    
      if (stylesheet) {
        stylesheet = stylesheet.sheet;
    
        if (stylesheet.addRule) {
          stylesheet.addRule(selector, rule);
        } else if (stylesheet.insertRule) {
          stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);
        }
      }
    }
    

    Once you get the DOM object through document.getElementById you can use the 'sheet' property to access the actual styleSheet. So just make sure that you provide an ID for the styleSheet you want to change. Even if it is an external CSS file, just give it an ID.

    And here is my test code:

    var index = 0;
    var items = [
      { selector: "h1", rules: "color:#3333BB;font: bold 18px Tahoma;padding: 12px 0 0 0;" },
      { selector: "p", rules: "padding:0;margin:0;background-color:#123456;color:#ABCDEF;"},
      { selector: "b", rules: "font-weight:normal;"},
      { selector: "i", rules: "color:#66FF66;" }
    ];
    
    function addRule(stylesheetId, selector, rule) {
      var stylesheet = document.getElementById(stylesheetId);
    
      if (stylesheet) {
        stylesheet = stylesheet.sheet;
    
        if (stylesheet.addRule) {
          stylesheet.addRule(selector, rule);
        } else if (stylesheet.insertRule) {
          stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);
        }
      }
    }
    
    $(document).ready(function () {
      $("button").click(function () {
        addRule("myStyles", items[index].selector, items[index].rules);
        index++;
      });
    });
    
    
    
    

    test

    Paragraph One

    Paragraph with bold and Italics

    Paragraph 3

提交回复
热议问题