如何在Javascript中获取`background-color`属性值?

时间:2014-08-11 07:45:48

标签: javascript

fiddle

以下代码提醒空字符串:

HTML:

<div id="test">test</div>

CSS:

#test{
    background-color: #f00;
}

SCRIPT:

alert(document.getElementById('test').style.backgroundColor)

但是如果我在javascript中设置bgcolor,那么它会提示bgcolor值:

document.getElementById('test').style.backgroundColor='#ff0';
alert(document.getElementById('test').style.backgroundColor) // rgb(255,255,0)

那么,如何在没有在样式表中定义的js中设置bgcolor值的情况下获取bgcolor值?

请注意,如果它来自用户代理的样式表而不是我的样式表,我根本不想获取值。

2 个答案:

答案 0 :(得分:2)

你没有看到.style的任何内容的原因是,这只会为你提供 元素的样式,而不是从样式表中获得的样式。

对于现代浏览器,您可以使用window.getComputedStyle获取元素的计算样式对象。对于IE8(以及更早版本,但是......),您可以使用.currentStyle来获得相同的功能。所以:

var element = document.getElementById('test');
var style;
if (window.getComputedStyle) {
    style = window.getComputedStyle(element);
} else {
    style = element.currentStyle;
}
if (!style) {
    // ...seriously old browser...
} else {
    alert(style.backgroundColor);
}

  

我只想获得样式表值。

getComputedStyle / currentStyle会为您提供,但也会为您提供浏览器的默认样式。

没有简单的界面只能从您自己的样式表中获取值,而不能从用户代理的默认样式表中获取值。您可能希望查看document.styleSheets property,这样您就可以访问各个已解析的样式表及其规则。但是你必须处理将这些规则应用于相关元素的逻辑,这当然是非平凡的。

答案 1 :(得分:-1)

使用此代码:

window.getComputedStyle(document.getElementById('test')).getPropertyValue("background-color")

希望这可能有用