JS_js获取元素样式style属性值,js获取元素css样式,getComputedStyle

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值