欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS動態(tài)獲取元素寬高的幾種方式

 更新時間:2024年09月18日 11:37:55   作者:亦黑迷失  
這篇文章主要介紹了js 動態(tài)獲取元素寬高的幾種方式,文章通過代碼示例和圖文結(jié)合的方式給大家介紹的非常詳細,對大家的學習或工作有一定的幫助,需要的朋友可以參考下

前期準備

我先準備了 2 個用來測試的 div

<div id="box1"></div>
<div id="box2"></div>

樣式如下,紅色的 box1 有使用 css 明確定義的寬高,綠色的 box2 則是只定義了高度,寬度為父元素(頁面)的 50%:

body {
  margin: 0;
}

#box1 {
  width: 100px;
  height: 100px;
  background-color: brown;
}

#box2 {
  width: 50%;
  height: 100px;
  background-color: cadetblue;
}

效果如下:

我通過 id 獲取到了 box1 和 box2 對象:

const box1 = document.getElementById('box1')
const box2 = document.getElementById('box2')

offsetWidth 與 offsetHeight

首先介紹的是 HTMLElement 的只讀屬性 offsetWidth 與 offsetHeight。我們可以直接打印查看 box1 和 box2 的寬高:

window.addEventListener('resize', () => {
  console.log(box1.offsetWidth, box1.offsetHeight)
  console.log(box2.offsetWidth)
})

結(jié)果如下,當文檔寬度為 642.5px 時,box1.offsetWidth 和 box1.offsetHeight 均為 100,box2.offsetWidth 的打印輸出為 321:

表明:

  • offsetWidthoffsetHeight 可以動態(tài)獲取元素的寬高;
  • 獲取的結(jié)果是不帶單位的;
  • 獲取的結(jié)果如果為小數(shù),會被取整。

getBoundingClientRect()

getBoundingClientRect() 是一個方法,使用方法如下:

const rect1 = box1.getBoundingClientRect()

返回的結(jié)果是一個 DOMRect 對象,其中除了元素的寬高信息外還有其它屬性:

打印查看 box1 和 box2 的寬度:

window.addEventListener('resize', () => {
  const rect1 = box1.getBoundingClientRect()
  const rect2 = box2.getBoundingClientRect()
  console.log(rect1.width)
  console.log(rect2.width)
})

結(jié)果如下:

表明:

  • getBoundingClientRect() 可以動態(tài)獲取元素的寬度(高度亦然);
  • 獲取的結(jié)果同 offsetWidth 一樣也是不帶單位的;
  • offsetWidth 不同的是,它的結(jié)果不會取整。

getComputedStyle()

getComputedStyle() 也是一個方法,使用方式如下:

const style1 = getComputedStyle(box1)

打印查看 style1,結(jié)果如下:

返回的對象基本上包含了 box1 的所有 css 屬性。我們只需要查看 width 屬性,所以可以:

window.addEventListener('resize', () => {
  const style1 = getComputedStyle(box1)
  const style2 = getComputedStyle(box2)
  console.log(style1.width)
  console.log(style2.width)
})

得到的結(jié)果如下:

表明:

  • getComputedStyle() 也可以動態(tài)地獲取元素的寬度;
  • 獲取的結(jié)果是帶單位的,這點與 getBoundingClientRect()offsetWidth 不同;
  • 它的結(jié)果也不會取整。

邊框、內(nèi)邊距的影響

現(xiàn)在我給 box1 的 css 添加上邊框 (border) 和內(nèi)邊距 (padding),研究對幾種獲取寬高的方式是否會產(chǎn)生影響:

#box1 {
  /* ...忽略之前的定義 */
  border: 1px solid #333;
  padding-left: 10px;
}
  • offsetWidth 與 offsetHeight

現(xiàn)在打印的結(jié)果中,box1.offsetWidth 就會為 112,box1.offsetHeight 為 102:

這說明 offsetWidthoffsetHeight 的值是會包含邊框和內(nèi)邊距的。

  • getBoundingClientRect()

rect1.width 的打印結(jié)果會約等于 box1 的 width(100px) + border(1px*2) + padding(10px) 的 112px:

可見 getBoundingClientRect() 獲取的寬高是會包含邊框和內(nèi)邊距的。

  • getComputedStyle()

即使添加了邊框與內(nèi)邊距,打印 style1.width 得到的結(jié)果依舊為 100px:

可見獲取的僅僅是 css 屬性中的 width 的值,與其它無關。

盒模型的影響

如果我再將 box1 的盒模型做出修改,改為 border-box

#box1 {
  /* ...忽略之前的定義 */
  box-sizing: border-box;
}

此時,無論是通過 offsetWidth 還是 getBoundingClientRect() 或是 getComputedStyle(),它們獲取到的關于 box1 寬度的結(jié)果,都為 100(或 100px):

以上就是JS動態(tài)獲取元素寬高的幾種方式的詳細內(nèi)容,更多關于JS獲取元素寬高的資料請關注腳本之家其它相關文章!

相關文章

最新評論