如果我使用insertRule添加了CSSOM的样式,我注意到了两件事。
添加的样式在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清晰的编辑:
如果将<style></style>标记附加到html的<head></head>中,则可以使用style.sheet.insertRule(styleString)应用样式,并且添加的样式将适用于文档。
如果您已经将该<style></style>附加到<head></head> (类似于<head><style></style></head> ),并尝试将<style></style>附加到其他地方(如<div><style></style></div> ),那么所有的样式都丢失了,并且不再应用。
这是正常的吗?
代码流:
作品:
<style>style.sheet.insertRule(styleString)添加样式不管用:
<style>style.sheet.insertRule(styleString)向<style>添加样式<style>我的另一个问题是,添加到<style></style>中的样式即使已应用于文档,也不会在Firebug中显示。
编辑更清晰:
如果我在不修改样式表的情况下重新追加style元素,则样式保留如下:
var style = document.querySelector('style');
document.head.appendChild(style);* {color: red}<p>Hello world</p>
但是,如果我用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./* CSS rules will be inserted with JS */<p>Hello world</p>
发布于 2016-04-20 04:45:31
这是因为<style>元素只有在附加到文档时才具有sheet属性。
因此,当您将其移动或从文档中移除它时,它们的sheet属性将设置为null。使用insertRule方法应用到它的每条规则都将消失,因为它们不在<style>的innerHTML中。
规格的相关部分:
用于CSS的
style块更新算法(text/css)如下:
如您所见,每次更新<style>元素时,都会创建一个新的CSS样式表(只有当.3和.4没有阻塞该进程时)。
小演示:
var style = document.createElement('style');
console.log('before being appended : '+ style.sheet)
document.body.appendChild(style);
console.log('after being appended : '+ style.sheet)
document.body.removeChild(style);
console.log('after being removed : '+ style.sheet)
https://stackoverflow.com/questions/36638076
复制相似问题