1. 程式人生 > >元素高度、寬度獲取 style currentStyle getComputedStyle getBoundingClientRect

元素高度、寬度獲取 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屬性。