在 IE 8 及以下版本中动态添加 @font-face 规则

发布于 2024-12-12 22:44:33 字数 358 浏览 2 评论 0原文

我使用 IE stylesheet.addRule() 方法添加 @font-face 规则。但是,@ 符号对于该方法的“选择器”参数来说是不允许的字符,因此我收到“无效参数”错误。

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

还有其他方法可以动态添加这些规则吗?

我尝试设置 style 元素的 innerHTML 属性,设置 styleSheet 属性的 cssText 属性,并将文本节点附加到 style 元素(这会导致 IE 崩溃)。

还有其他方法可以尝试吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吻风 2024-12-19 22:44:34

设置 cssText 属性确实有效,但您必须在将 @font-face 规则添加到文档之前将样式元素插入到文档中。例如...

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

据我所知,在将样式元素插入页面之前完全可以设置其他类型的CSS规则,但@font-face不行。

例如...这工作正常:

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

但这会使 IE 8 及以下版本崩溃:

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文