getComputedStyle(“元素”, “伪类”)

<div id="caseroul" style="width: 500px;"></div>

获取单个属性值

getComputedStyle(document.getElementById('caseroul'),null).getPropertyValue('width'); //500px
getComputedStyle(document.getElementById('caseroul'),null).width; //500px

获取全部属性值

getComputedStyle(document.getElementById('caseroul'),null)

在这里插入图片描述

处理后的数据

<style>
.button {
    height: 2em;
    border: 0;
    border-radius: .2em;
    background-color: #34538b;
    color: #fff;
    font-size: 12px;
    font-weight: bold;
}
</style>
<input type="button" id="button" class="button" value="点击我,显示我" />
<p id="detail"></p>
<script>
var oButton = document.getElementById("button"),
    oDetail = document.getElementById("detail");

if (oButton && oDetail) {
    oButton.onclick = function() {
        var oStyle = this.currentStyle? this.currentStyle : window.getComputedStyle(this, false);
        
        var key, html = '本按钮CSS属性名和属性值依次为('+ !!this.currentStyle +'):';
        if (typeof oStyle === "object") {
            for (key in oStyle) {
                if (/^[a-z]/i.test(key) && oStyle[key]) {
                    html = html + '' + key + ":" + oStyle[key] + '';
                }
            }
        } else {
            html += '无法获取CSS样式!';
        }
        oDetail.innerHTML = html;
    };
}
</script>