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

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

更多信息:

  • 有关getComputedStyle()<的更多信息,请参阅此页面/code>.
  • 请参阅此页面 有关 currentStyle (IE) 的更多信息.
  • 有关浏览器兼容性问题的更多信息,请参阅此页面.
  • 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天全站免登陆