我在下面有以下代码,我正在尝试设置背景颜色。但是,背景颜色作为空字符串返回。我不确定为什么......它与javascript类型有关吗?
function function1(){
var color = document.getElementById('rg_vw.national_avg').style.backgroundColor;
//this below appears as an empty alert at runtime. it's an empty string.
alert(color)
}
正如一个完整性检查,如果我使用'value'属性,它会打印出该特定字段的正确值...所以我对于为什么backgroundColor是一个空字符串感到有点沮丧。< / p>
//this works just fine
var value = document.getElementById('rg_vw.national_avg').value
alert(value)
答案 0 :(得分:17)
除非您在元素本身上直接定义了backgroundColor,否则必须使用getComputedStyle()
或currentStyle
来获取样式属性的值。
与多个浏览器兼容的方法如下所示:
function getStyle(el,styleProp)
{
if (el.currentStyle)
return el.currentStyle[styleProp];
return document.defaultView.getComputedStyle(el,null)[styleProp];
}
您可以在jsFiddle上看到一个有效的例子。
更多信息: