我正在尝试将样式规则直接插入到文档的头部。
它插入样式元素,但不插入代码本身。没有错误或任何东西。
var thumbStyles = document.createElement("style");
document.head.appendChild(thumbStyles);
thumbStyles.sheet.insertRule(
"figure#styleThumbs { \
position: absolute; \
left: 0px; \
bottom: 0px; \
} \
")
thumbStyles.sheet.insertRule(
"figure#styleThumbs img { \
outline: 1px solid black; \
cursor: pointer; \
opacity: 0.75; \
} \
")
thumbStyles.sheet.insertRule(
"figure#styleThumbs img:hover { \
outline: 1px solid red; \
opacity: 1.0; \
} \
");
最佳答案
插入的 CSS 不会显示在 DOM 中,但它确实有效。
var thumbStyles = document.createElement("style");
document.head.appendChild(thumbStyles);
thumbStyles.sheet.insertRule(`#test{
background-color: dodgerblue;
}`);
<div id="test">
This is a test
</div>
关于javascript - insertRule() 不插入规则但没有给出任何错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63349636/