js获取容器的大小(宽高)

通过JS获取盒模型对应的宽和高,有以下几种方法:

1. dom.style.width/height

这种方式只能取到dom元素内联样式所设置的宽高,也就是说如果该节点的样式是在style标签中或外联的CSS文件中设置的话,通过这种方法是获取不到dom的宽高的。

2. dom.currentStyle.width/height

这种方式获取的是在页面渲染完成后的结果,就是说不管是哪种方式设置的样式,都能获取到。

但这种方式只有IE浏览器支持,在其他的浏览器中会报错的

3. window.getComputedStyle(dom).width/height

这种方式的原理和2是一样的,这个可以兼容更多的浏览器,通用性好一些。

4. dom.getBoundingClientRect().width/height

这种方式是根据元素在视窗中的绝对位置来获取宽高的

5.dom.offsetWidth/offsetHeight

最常用的,也是兼容最好的。这种方式获取的宽高包含border,且不带单位

<style>
    #container2{
        width: 200px;
        height: 200px;
        border:1px solid red;
        padding-top:20px;
    }
</style>
<body>
    <div id="container1" style="width:100px;height:100px;border:1px solid yellow;">
        内联样式盒子
    </div>
    <div id="container2">非内联样式盒子</div>
</body>
<script>
   var con1 = document.getElementById('container1');
   console.log(con1.style.height); // 100px 只有内联样式中才能获取到 
   console.log(window.getComputedStyle(con1).height); //100px 
   console.log(con1.offsetWidth);//102 注意没有单位

    var con2 = document.getElementById('container2');
   // alert(con2.currentStyle.height); //ie中才生效,否则控制台报错
   console.log(window.getComputedStyle(con2).height); // 200px;
   console.log(con2.offsetWidth); // 202  注意没有单位
</script>


转载自原文:https://blog.csdn.net/weixin_37347069/article/details/84800438 
 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值