javascript - insertRule() 不插入规则但没有给出任何错误

标签 javascript html css nodes

我正在尝试将样式规则直接插入到文档的头部。

它插入样式元素,但不插入代码本身。没有错误或任何东西。

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; \
    } \
    ");

Picture of HTML Head with style but no style code

I also asked this question on FCC but have no answers

最佳答案

插入的 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/

相关文章:

javascript - 社交媒体按钮会减慢网站加载时间

打印时 CSS 元素在 Chrome 中不起作用

javascript - 在一页中实现多个带有自定义按钮的TinyMCE编辑器

javascript - 数组原型(prototype) toString() 与对象 toString()

javascript - 如何选择位于不同跨度且也是类元素的元素?

css - 如何在不使用额外的 div 的情况下使同一行上的文本使用不同的字体?

jquery - 为什么我的 css 动画只在第一次触发时播放?而不是再次触发后续事件?

javascript - 多个 div 的 jQuery 范围 slider 值框

javascript - 返回历史记录无法正常工作

javascript - 使用 toggleClass 缩放对象后删除 :hover effect,