如何在javascript中获取元素的背景颜色?

时间:2013-06-16 17:41:55

标签: javascript css

我需要获取之前由样式表定义的元素的背景颜色,以便确定将使用javascript动态创建的新元素的样式。

我尝试使用'backgroundColor'属性,但返回值为空。需要首先使用js设置该值,然后可以使用属性(不是十六进制)检索它。是否有其他替代方案而不必修改元素?喜欢使用offsetWidth?

CSS:

#mybox {
   width: 100px;
   height: 100px;
   margin: auto;
   background-color: #eb5;
}
#buttons {
   text-align: center;
}

HTML:

<div id="mybox"></div> <div id="buttons">
    <input type="button" value="set" onclick="setColor('#ddd')" />
    &nbsp;
    <input type="button" value="get" onclick="getColor()" />
</div>

JS:

function getColor(color){
    var box = document.getElementById("mybox");
    alert(box.style.backgroundColor);
}
function setColor(color){
    var box = document.getElementById("mybox");
    box.style.backgroundColor = color;
}

的jsfiddle: http://jsfiddle.net/mevmike/FjkYA/

1 个答案:

答案 0 :(得分:1)

试试这个:

function getStyle(element, property) {
    if (element.currentStyle)
        return this.currentStyle[property];
    else if (getComputedStyle)
        return getComputedStyle(element, null)[property];
    else
        return element.style[property];
}

将此代码放在脚本文件的开头,并以这种方式访问​​

function getColor(color){
    var box = document.getElementById("mybox");
    alert(getStyle(box, 'backgroundColor'));
}

编辑:“压缩”版本

function getStyle(element, property) {
    return getComputedStyle ? getComputedStyle(element, null)[property] : 
    element.currentStyle ? element.currentStyle[property] : element.style[property];
}
相关问题