Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

html - style.backgroundColor is an empty string in 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)
}

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)   
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...