【问题标题】:insertRule() not inserting rule but not giving any errorsinsertRule() 没有插入规则但没有给出任何错误
【发布时间】:2020-11-30 14:45:51
【问题描述】:

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

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

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

【问题讨论】:

  • 为什么要用JS把这个样式加到头部?
  • 它应该教我们关于节点的知识,这是项目的一部分

标签: javascript html css nodes


【解决方案1】:

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

【讨论】:

  • 谢谢。第二次我从使用引号改为使用反引号
猜你喜欢
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
  • 2019-03-16
  • 1970-01-01
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多