为什么样式不可见,样式标签在使用CSSOM的insertRule后无法重新附加

Que*_*les 6 html javascript css cssom

如果我用CSSOM添加了样式,insertRule我注意到了两件事.

在Firebug中查看时,添加的样式不会出现在html中.

如果附加样式标记(例如:从头部移动到主体)到另一个元素(在Firefox和Chrome中发生),则添加的样式不起作用.

如果在添加标记后添加样式,则它们可以正常工作.他们仍然没有在Firebug中展示.附加表格时必须重新分配(重新?),这使得它看起来更奇怪.

因为没有在Firebug中显示,它可能是Firebug的怪癖,但是没有动态添加的常规样式显示出来.

对于追加后不起作用的样式我想知道这是否是标准,因为这发生在Firefox和Chrome中.看看标准,我没有看到任何关于这一点.除非我只是不理解他们.

var style = document.createElement('style'),
    sheet = style.sheet;
document.head.appendChild(style);
//When line 6 is un-commented the styles work
//if line 8 is also commented out.
//document.querySelector('.container').appendChild(style);
//Get the sheet when line 6 is un-commented
sheet = style.sheet
sheet.insertRule('.test{color: red}');
document.querySelector('.container').appendChild(style);
//styles don't apply after the previous line
Run Code Online (Sandbox Code Playgroud)

为清晰起见编辑:

如果您<style></style><head></head>html中添加标签,则可以应用样式style.sheet.insertRule(styleString),并且添加的样式将适用于该文档.

如果您已经是附加<style></style><head></head><head><style></style></head>,并试图追加<style></style>其他地方像<div><style></style></div>所有样式都将丢失,而不要再次申请.

这是正常的吗?

代码流程:

作品:

  1. 追加<style>任何地方
  2. 添加样式 style.sheet.insertRule(styleString)

不起作用:

  1. 追加<style>任何地方
  2. style.sheet.insertRule(styleString)to 添加样式<style>
  3. <style>其他地方添加相同的内容

我的另一个问题是添加的样式即使已应用于文档<style></style>也不会显示Firebug.

编辑更清晰:

如果我在style没有修改样式表的情况下重新添加元素,则样式仍然存在:

var style = document.querySelector('style');
document.head.appendChild(style);
Run Code Online (Sandbox Code Playgroud)
* {color: red}
Run Code Online (Sandbox Code Playgroud)
<p>Hello world</p>
Run Code Online (Sandbox Code Playgroud)

但是如果我用JS改变了样式表,则撤消更改:

var style = document.querySelector('style'),
    sheet = style.sheet;
sheet.insertRule('* {color: red}', 0);
document.head.appendChild(style); //Comment this line out, and this works.
Run Code Online (Sandbox Code Playgroud)
/* CSS rules will be inserted with JS */
Run Code Online (Sandbox Code Playgroud)
<p>Hello world</p>
Run Code Online (Sandbox Code Playgroud)

Kai*_*ido 6

这是因为<style>元素只有sheet在附加到doc 时才具有属性.
因此,当您移动它或从文档中删除它时,它们的sheet属性将被设置为null.你使用应用到它的每一个规则的insertRule方法将会消失,因为他们不是里面<style>innerHTML.


相关部分的规格:

更新一个style对CSS(算法text/css)如下:

  1. 设元素是样式元素.

  2. 如果element具有关联的CSS样式表,请删除相关的CSS样式表.

  3. 如果元素不在Document中,则中止这些步骤.

  4. 如果内容安全策略[...]阻止了Should元素的内联行为,则中止这些步骤.[CSP]

  5. 创建具有以下属性的CSS样式表:...

如您所见,每次<style>更新元素时​​,都会创建一个新的CSS样式表(仅当.3.4不阻止该过程时).


小演示:

var style = document.createElement('style');
snippet.log('before being appended : '+ style.sheet)
document.body.appendChild(style); 
snippet.log('after being appended : '+ style.sheet)
document.body.removeChild(style);
snippet.log('after being removed : '+ style.sheet)
Run Code Online (Sandbox Code Playgroud)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Run Code Online (Sandbox Code Playgroud)