我正在寻找一种使用JavaScript将<style>
标签插入HTML页面的方法。
目前我发现的最好的方式:
var divNode = document.createElement("div");
divNode.innerHTML = "<br><style>h1 { background: red; }</style>";
document.body.appendChild(divNode);
这在Firefox、Opera和Internet Explorer中工作,但在Google Chrome中不起作用。而且在IE中,前面的<br>
有点丑。
是否有人知道创建一个<style>
标签的方法:
更好看
与Chrome兼容?
或者可能:
这是我应该避免的非标准做法
三个可用的浏览器很棒,谁还使用Chrome呢?
document.head
在所有主流浏览器中都得到支持。 - Rob Wdocument.querySelector("head")
?根据来源,它也支持IE8。 - allenhwkimquerySelector()
的引入;今天,我可能会选择自IE9起可用的document.head
。 - Christophstyle.styleSheet.cssText
之前,我必须将样式元素附加到头部。在附加之前,style.styleSheet
为null。 - Will Hawker