How do I load css rules dynamically in Webkit (Safari/Chrome)?

后端 未结 8 1868
悲哀的现实
悲哀的现实 2020-12-10 17:16

I currently have issues in Webkit(Safari and Chrome) were I try to load dynamically (innerHTML) some html into a div, the html contains css rules (...), after the html gets

8条回答
  •  爱一瞬间的悲伤
    2020-12-10 17:29

    Besides the style tag based versions above, you can also add styles using javascript directly:

    var style = document.getElementById('some-style-tag');
    var sheet = style.sheet;
    sheet.insertRule('.mydiv { background-color: ' + color + '; }', sheet.cssRules.length);
    

    This has the advantage of being able to use variables without having to resort to cssText/innerHTML.

    Keep in mind that on webkit based browsers this can be slow if you are inserting a lot of rules. There is a bug open to fix this performance issue in webkit (https://bugs.webkit.org/show_bug.cgi?id=36303). Until then, you can use style tags for bulk inserts.

    This is the W3C standard way of inserting style rules, but it is not supported by any version of IE: http://www.quirksmode.org/dom/w3c_css.html

提交回复
热议问题