style.backgroundColor 是 JavaScript 中的空字符串 [英] style.backgroundColor is an empty string in JavaScript
问题描述
我在下面的代码中尝试设置背景颜色.但是,背景颜色作为空字符串返回.我不知道为什么...这与 javascript 类型有关吗?
I have the following code below that I'm trying to set a background color. However, the background color returns as an empty string. I'm not sure why...Does it have something to do with javascript types?
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 是空字符串感到有点沮丧.
Just as a sanity check, if I use the 'value' property, it prints out the correct value for that particular field...so I'm just a bit frustrated as to why the backgroundColor is an empty string.
//this works just fine
var value = document.getElementById('rg_vw.national_avg').value
alert(value)
推荐答案
除非你直接在元素本身上定义了 backgroundColor,否则你必须使用 getComputedStyle()
或 currentStyle
获取样式属性的值.
Unless you have directly defined the backgroundColor on the element itself, you have to use getComputedStyle()
or currentStyle
to get the value of a style property.
与多个浏览器兼容的方法如下所示:
A method that is compatible with multiple browsers would look like this:
function getStyle(el,styleProp)
{
if (el.currentStyle)
return el.currentStyle[styleProp];
return document.defaultView.getComputedStyle(el,null)[styleProp];
}
您可以在 jsFiddle 上看到一个工作示例.
You can see a working example on jsFiddle.
更多信息:
- See this page for more information about
getComputedStyle()
. - See this page for more information about
currentStyle
(IE). - See this page for more information about browser compatibility issues.
这篇关于style.backgroundColor 是 JavaScript 中的空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!