0

我需要获取先前由样式表定义的元素的背景颜色,以确定将使用 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/

4

1 回答 1

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];
}
于 2013-06-16T17:47:09.220 回答