<分区>
标签 javascript css
<分区>
想知道如何更新样式表。
这在我能够测试的任何地方都有效,但不确定它是否是最佳解决方案:
runDemo();
var css = document.getElementsByTagName("style")[0];
getRule(css.sheet.rules, "div").
style.width = 80 / [4, 5, 7][parseInt(Math.random() * 3)] + "%";
function getRule(rules, selector) {
for (var i in rules) {
if (rules[i].selectorText == selector)
return rules[i];
}
return null;
}
function runDemo() {
for (var i = Math.random() * 10 + 5; i > 0; i--) {
var d = document.createElement("div");
d.innerText = parseInt(i + 1);
document.body.appendChild(d);
}
}
body {
display: flex;
flex-flow: row wrap;
}
div {
margin: 10px;
padding: 3;
text-align: center;
border: 1px solid blue;
}
最佳答案
我不建议以这种方式编辑样式规则。最好添加或删除整个样式表。这样可以更轻松地管理您的样式。
您可以在此处找到操作方法:Add stylesheet to Head using javascript in body
关于javascript - 样式表更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58235737/