style.backgroundColor是JavaScript中的空字符串

did*_*ido 7 html javascript properties

我在下面有以下代码,我正在尝试设置背景颜色.但是,背景颜色作为空字符串返回.我不确定为什么......这与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)
}
Run Code Online (Sandbox Code Playgroud)

正如一个完整性检查,如果我使用'value'属性,它会打印出该特定字段的正确值...所以我对于为什么backgroundColor是一个空字符串感到有点沮丧.

//this works just fine
var value = document.getElementById('rg_vw.national_avg').value
alert(value)   
Run Code Online (Sandbox Code Playgroud)

Eli*_*ing 18

除非您在元素本身上直接定义了backgroundColor,否则必须使用getComputedStyle()currentStyle获取样式属性的值.

与多个浏览器兼容的方法如下所示:

function getStyle(el,styleProp)
{
    if (el.currentStyle)
        return el.currentStyle[styleProp];

    return document.defaultView.getComputedStyle(el,null)[styleProp];
}
Run Code Online (Sandbox Code Playgroud)

你可以在jsFiddle上看到一个工作示例.

更多信息:

  • 有关的更多信息,请参阅此页面getComputedStyle().
  • 有关(IE)的更多信息,请参阅此页面currentStyle.
  • 有关浏览器兼容性问题的详细信息,请参阅此页面