getPropertyValue以及getAttribute方法获取元素背景色实例页面

回到相关文章 »

代码:

CSS代码:
.button {
    height: 2em;
    border: 0;
    border-radius: .2em;
    background-color: #34538b;
    color: #fff;
    font-size: 12px;
    font-weight: bold;
}
                
HTML代码:
<input type="button" id="button" class="button" value="点击我,显示背景色" />
                
JS代码:
var oButton = document.getElementById("button");

if (oButton) {
    oButton.onclick = function() {
        var oStyle = this.currentStyle? this.currentStyle : window.getComputedStyle(this, null);
        if (oStyle.getPropertyValue) {
            alert("getPropertyValue下背景色:" + oStyle.getPropertyValue("background-color"));
        } else {
            alert("getAttribute下背景色:" + oStyle.getAttribute("backgroundColor"));
        }
    };
}
                

效果: