如何从JavaScript中的<style>标签获取样式属性?</style>

时间:2014-02-06 15:27:58

标签: javascript html css html5 css3

JavaScript中有一种方法: - element.style.anyProperty;但是会​​从style attribute返回一个css值,但不会从<style>标记中获取它。如何在JavaScript中获取tag not attribute中的任何属性?例如: -

<style>
    div{background:red;}
</style>

现在我如何获得任何元素的背景属性或当前背景?

3 个答案:

答案 0 :(得分:1)

您可以使用document.styleSheets,它会返回CSSStyleSheet objects列表。

然后,您可以使用这些对象来获取每个样式标记中包含的所有CSS规则。

对于你的风格示例,你应该得到:

var styleSheetList = document.styleSheets;
var first_rule = styleSheetList[0].cssRules[0];
console.log( first_rule.selectorText);  //should print "div"
console.log( first_rule.style.background);  //should print "red"

请注意:

  1. 您还可以在运行时更改这些对象以更改页面样式
  2. 您只获得内联样式的规则,而不是来自外部资源的规则
  3. 所有css属性都在CamelCase中转换,例如: background-color表示为backgroundColor

答案 1 :(得分:0)

此代码检查样式表规则,如果找到白色,则将其设置为红色。

var ssObj;
if (document.styleSheets[0].cssRules) {
  ssObj = document.styleSheets[0].cssRules;
}
if (document.styleSheets[0].rules) {
  ssObj = document.styleSheets[0].rules;
}
for (var i = 0; i < ssObj.length; i++) {
  if (ssObj[i].style.color == 'white') {
    ssObj[i].style.setProperty('color', 'red', null);
  }
}

正如您所看到的,有两种方法可以根据浏览器获取规则,但是一旦有了这些规则,其余的就是直接的。

答案 2 :(得分:0)

这样的事情:

CSS标记:

<style>
  #myID { background:red; }
</style>

Javascript标记:

document.getElementById("myID");