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

2020-05-27 08:26发布

问题:

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 a 'invalid argument' error.

s.addrule("@font-face", "font-family: 'Font Name'; src:url('/fonts/font.eot') etc...)";

Is there some other way to dynamically add these rules?

I've tried setting the innerHTML property of the style element, setting the cssText property of the styleSheet property, and appending a text node to the style element as well (which crashes IE).

Any other methods to try?

回答1:

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);