js 不同浏览器的宽度获取

本文介绍了一种兼容多种浏览器的方法来获取HTML元素的实际宽度,包括IE和其他现代浏览器如Chrome和Firefox。通过使用`getComputedStyle`和针对IE的特定属性,确保了跨浏览器的一致性。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>Document</title>
    <style>
        .box{
            width: 100px;
            height: 100px;
            background-color: yellowgreen;
            padding: 20px;
        }
    </style>
</head>
<body>
    <div id="box" class="box"></div>
    <script>
    var oDiv = document.getElementById('box');

    oDiv.onclick = function (){
        //this.style.width 获取的是行间样式(设定的也是行间样式)
        //alert(this.style.width);
        

        //  给 ie浏览器使用的  obj.currentStyle[你的属性]
        //alert(oDiv.currentStyle['width']);
        
        // chrome 、firefox、ie9+
        // alert(getComputedStyle(谁,false)[attr]);
        alert(getComputedStyle(oDiv,false)['width']);
    }

    </script>
</body>
</html>

 

转载于:https://www.cnblogs.com/jinsuo/p/6825194.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值