Dynamically adding @font-face rule in IE 8 and less

前端 未结 1 2087
遇见更好的自我
遇见更好的自我 2021-02-06 05:21

I\'m adding @font-face rules using IEs stylesheet.addRule() method. However, the @ symbol is a disallowed character for the \'selector\' argument of that method so I\'m getting

1条回答
  •  北荒
    北荒 (楼主)
    2021-02-06 06:01

    Setting the cssText property does work, but you MUST insert the style element into the document before adding the @font-face rule to the document. Eg...

    var s = document.createElement('style');
    s.type = "text/css";
    document.getElementsByTagName('head')[0].appendChild(s);
    s.styleSheet.cssText = "@font-face {" + rule + "}";
    

    As far as I can tell it is perfectly possible to set other types of CSS rules before inserting the style element into the page, but not @font-face.

    Eg... this works fine:

    var s = document.createElement('style');
    s.type = "text/css";
    s.styleSheet.cssText = "body { background: red}";
    document.getElementsByTagName('head')[0].appendChild(s);
    

    But this crashes IE 8 and less:

    var s = document.createElement('style');
    s.type = "text/css";
    s.styleSheet.cssText = "@font-face {" + rule + "}";
    document.getElementsByTagName('head')[0].appendChild(s);
    

    0 讨论(0)
提交回复
热议问题