动态添加@ font-face规则在IE 8和更少 [英] Dynamically adding @font-face rule in IE 8 and less

查看:1185
本文介绍了动态添加@ font-face规则在IE 8和更少的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用IEs stylesheet.addRule()方法添加@ font-face规则。但是,@符号是该方法的'selector'参数的不允许的字符,所以我得到一个无效的参数错误。

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?

我已经尝试设置style元素的innerHTML属性,设置styleSheet属性的cssText属性,以及在style元素上附加一个文本节点(导致IE崩溃)。

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

任何其他方法尝试?

推荐答案

设置cssText属性可以工作,在将@ font-face规则添加到文档之前,将样式元素插入到文档中。例如...

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 + "}";

据我所知,插入风格之前完全可以设置其他类型的CSS规则元素到页面,但不是@ font-face。

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

但这会导致IE 8及更低版本崩溃:

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

这篇关于动态添加@ font-face规则在IE 8和更少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆