我下面有以下代码,我正在尝试设置背景颜色。但是,背景颜色返回为空字符串。我不知道为什么......它与 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 是一个空字符串感到有点沮丧。
//this works just fine
var value = document.getElementById('rg_vw.national_avg').value
alert(value)
除非您直接在元素本身上定义了背景颜色,否则您必须使用getComputedStyle()
or currentStyle
获取样式属性的值。
与多个浏览器兼容的方法如下所示:
function getStyle(el,styleProp)
{
if (el.currentStyle)
return el.currentStyle[styleProp];
return document.defaultView.getComputedStyle(el,null)[styleProp];
}
你可以看到一个工作示例jsFiddle http://jsfiddle.net/4p65N/.
更多信息:
- See 这一页 https://developer.mozilla.org/en/DOM/window.getComputedStyle欲了解更多信息
getComputedStyle()
.
- See 这一页 http://msdn.microsoft.com/en-us/library/ie/ms535231%28v=vs.85%29.aspx欲了解更多信息
currentStyle
(IE).
- See 这一页 http://www.quirksmode.org/dom/getstyles.html有关浏览器兼容性问题的更多信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)