如何使用Javascript添加CSS规则(如强{颜色:红色})?
当前回答
这是我在最后一个样式表列表的末尾添加css规则的解决方案:
var css = new function()
{
function addStyleSheet()
{
let head = document.head;
let style = document.createElement("style");
head.appendChild(style);
}
this.insert = function(rule)
{
if(document.styleSheets.length == 0) { addStyleSheet(); }
let sheet = document.styleSheets[document.styleSheets.length - 1];
let rules = sheet.rules;
sheet.insertRule(rule, rules.length);
}
}
css.insert("body { background-color: red }");
其他回答
最短一行 //一个函数: const addCSS =css => document.head.appendChild(document.createElement("style")).innerHTML=css; / /使用方法: addCSS(“身体{背景:红色;}”)
简单而直接的方法是在文档中创建并添加一个新的样式节点。
// 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.innerText = styles
document.head.appendChild(styleSheet)
这个简单的例子在html头部添加<style>
var sheet = document.createElement('style');
sheet.innerHTML = "table th{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ "table ul { margin-top: 0 !important; margin-bottom: 0 !important;}\n"
+ "table td{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ ".messages.error{display:none !important;}\n"
+ ".messages.status{display:none !important;} ";
document.body.appendChild(sheet); // append in body
document.head.appendChild(sheet); // append in head
动态样式——用JavaScript操作CSS
您可以逐个元素添加类或样式属性。
例如:
<a name="myelement" onclick="this.style.color='#FF0';">text</a>
你可以这样做。背景,this.style。字体大小等。你也可以使用同样的方法应用一个样式
this.className='classname';
如果你想在javascript函数中做到这一点,你可以使用getElementByID而不是'this'。
本·布兰克(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);
}