style.backgroundColor是JavaScript中的一个空字符串 [英] style.backgroundColor is an empty string in JavaScript
问题描述
我在下面有下面的代码,我试图设置背景颜色。但是,背景颜色以空字符串的形式返回。我不知道为什么...它是否与JavaScript类型有关?
function function1(){
var color = document.getElementById('rg_vw.national_avg')。style.backgroundColor;
//下面的这个在运行时显示为空警报。它是一个空字符串。
alert(color)
}
就像一个理智检查一样,如果我使用'value'属性,它会打印出特定字段的正确值...所以我只是有点沮丧,为什么backgroundColor是一个空字符串。
//这工作正常
var value = document.getElementById('rg_vw.national_avg')。value
alert(value)
除非您直接在元素本身上定义了backgroundColor,否则您必须使用 getComputedStyle()
或 currentStyle
来获取样式属性的值。
与多个浏览器兼容的方法如下所示:
函数getStyle(el,styleProp)
{
if(el.currentStyle)
return el.currentStyle [styleProp];
return document.defaultView.getComputedStyle(el,null)[styleProp];
}
更多信息:
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)
}
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)
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];
}
You can see a working example on jsFiddle.
More information:
- 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屋!