style.backgroundColor是JavaScript中的一个空字符串 [英] style.backgroundColor is an empty string in JavaScript

查看:121
本文介绍了style.backgroundColor是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];
}

您可以在

更多信息:





  • 请参阅此页以了解有关 getComputedStyle()

  • 请参阅 this page 了解更多关于 currentStyle (IE)的信息。
  • >
  • 有关浏览器兼容性问题的更多信息,请参阅此页面


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆