【发布时间】:2016-08-06 21:23:15
【问题描述】:
如果我使用 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>
【问题讨论】:
-
不确定问题是什么?
-
主要是在追加样式标签后样式不适用,该样式标签已经使用 insertRule normal 添加了样式?
-
如果正确解释问题,这将类似于
div{color:green};div{color:blue}blue将color设置为div,因为它是最后一个声明。见stackoverflow.com/questions/1043001/… -
这似乎不是问题所在。如果我手动将嵌入的
<style>添加到 html 中,然后使用appendChild移动它,那么该标签中的手写样式就会应用。 -
“如果我将嵌入的 是的。
html元素处的style属性的特异性应优先考虑。您是否阅读了链接问题的所有答案?另请参阅stackoverflow.com/questions/2809024/points-in-css-specificity、w3.org/TR/CSS2/cascade.html#specificity
标签: javascript html css cssom