如何使用Javascript添加CSS规则(例如strong { color: red }
)?
发布于 2009-04-01 23:57:21
您也可以使用DOM Level 2CSS interface(MDN)来完成此操作:
var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);
除了(自然地) IE8和...on之外的所有内容,它们使用了自己略有不同的措辞:
sheet.addRule('strong', 'color: red;', -1);
与createElement-set-innerHTML方法相比,这种方法在理论上有一个优势,因为您不必担心在innerHTML中放入特殊的HTML字符,但在实践中,样式元素是遗留HTML中的CDATA,而且‘<’和‘&’很少在样式表中使用。
在像这样开始添加样式表之前,您确实需要一个适当的样式表。它可以是任何现有的活动样式表:外部的、嵌入式的或空的,都无关紧要。如果没有,目前创建它的唯一标准方法就是使用createElement。
发布于 2009-04-02 06:24:07
简单直接的方法是创建一个新的style
节点并将其添加到文档中。
// Your CSS as text
var styles = `
.qwebirc-qui .ircwindow div {
font-family: Georgia,Cambria,"Times New Roman",Times,serif;
margin: 26px auto 0 auto;
max-width: 650px;
}
.qwebirc-qui .lines {
font-size: 18px;
line-height: 1.58;
letter-spacing: -.004em;
}
.qwebirc-qui .nicklist a {
margin: 6px;
}
`
var styleSheet = document.createElement("style")
styleSheet.type = "text/css"
styleSheet.innerText = styles
document.head.appendChild(styleSheet)
发布于 2011-06-02 15:31:48
Ben Blank的解决方案在我的IE8中是行不通的。
然而,这在IE8中确实起作用了
function addCss(cssCode) {
var styleElement = document.createElement("style");
styleElement.type = "text/css";
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = cssCode;
} else {
styleElement.appendChild(document.createTextNode(cssCode));
}
document.getElementsByTagName("head")[0].appendChild(styleElement);
}
https://stackoverflow.com/questions/707565
复制相似问题