元素高度、宽度获取 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=" 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