How do you add CSS with Javascript?

前端 未结 14 2629
旧时难觅i
旧时难觅i 2020-11-22 17:18

How do you add CSS rules (eg strong { color: red }) by use of Javascript?

14条回答
  •  心在旅途
    2020-11-22 17:45

    You can also do this using DOM Level 2 CSS interfaces (MDN):

    var sheet = window.document.styleSheets[0];
    sheet.insertRule('strong { color: red; }', sheet.cssRules.length);
    

    ...on all but (naturally) IE8 and prior, which uses its own marginally-different wording:

    sheet.addRule('strong', 'color: red;', -1);
    

    There is a theoretical advantage in this compared to the createElement-set-innerHTML method, in that you don't have to worry about putting special HTML characters in the innerHTML, but in practice style elements are CDATA in legacy HTML, and ‘<’ and ‘&’ are rarely used in stylesheets anyway.

    You do need a stylesheet in place before you can started appending to it like this. That can be any existing active stylesheet: external, embedded or empty, it doesn't matter. If there isn't one, the only standard way to create it at the moment is with createElement.

提交回复
热议问题