元素高度、宽度获取 style currentStyle getComputedStyle getBoundingClientRect

1、示例代码

(1)html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>js获取宽度</title>
        <style type="text/css">
            #app{
                width: 300px !important;
            }
        </style>
        <link rel="stylesheet" type="text/css" href="css/style.css"/>
    </head>
    <body>
        <div id="app" style="width: 200px;">
            1
        </div>
        <script type="text/javascript">
            let app = document.getElementById('app')
            //不准确 只能获取内敛样式属性值
            console.log(app.style.width)
            //currentStyle:该属性只兼容IE(从IE6就开始兼容了),不兼容火狐和谷歌
            // console.log(app.currentStyle.width)
            // getComputedStyle仅仅ie 6 7 8不支持
            console.log(window.getComputedStyle(app).width)
            // 返回300 单位是px。除了 width 和 height 外的属性都是相对于视口的左上角位置而言的
            console.log(app.getBoundingClientRect().width)
        </script>
    </body>
</html>

(2)css

#app{
    width: 100px;
}

2、方法区别

(1)dom.style.width

只能获取内敛样式。因此是不准确的。

 

(2)dom.currentStyle.width

https://developer.mozilla.org/zh-CN/docs/Web/API/Element/currentStyle

Element.currentStyle 是一个与 window.getComputedStyle方法功能相同的属性。这个属性实现在旧版本的IE浏览器中。

 

(3)window.getComputedStyle(dom).width

https://developer.mozilla.org/zh-CN/docs/Web/API/Window/getComputedStyle

Window.getComputedStyle()方法返回一个对象,该对象在应用活动样式表并解析这些值可能包含的任何基本计算后报告元素的所有CSS属性的值。因此输出的值是准确的。

但是有兼容性:

https://caniuse.com/#search=getComputedStyle

ie6-8不支持。

 

(4)dom.getBoundingClientRect().width

https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect

返回值是一个 DOMRect 对象,这个对象是由该元素的 getClientRects() 方法返回的一组矩形的集合, 即:是与该元素相关的CSS 边框集合 。

DOMRect 对象包含了一组用于描述边框的只读属性——left、top、right和bottom,单位为像素。除了 width 和 height 外的属性都是相对于视口的左上角位置而言的。

低版本的IE也有兼容性问题:

https://caniuse.com/#search=getBoundingClientRect

有的浏览器不包含width和height属性。

 

转载于:https://www.cnblogs.com/mengfangui/p/10208370.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值