iT邦幫忙

0

Javascript 輕鬆獲得元素大小、位置的實用方法| getBoundingClientRect()

  • 分享至 

  • xImage
  •  

返回值是一個 DOMRect物件 ,用px 為單位描述這個矩形的位置跟大小。
其中包含 x/y/width/height/top/right/bottom/left 等屬性。

https://ithelp.ithome.com.tw/upload/images/20240407/201354144RsGyGrile.png
圖截自: 那些被忽略但很好用的 Web API / GetBoundingClientRect

然後注意他的寬跟高是有包含border寬度的;而位置屬性則是從viewport(視窗)的左上角開始算。

例如下面是我測量我的nav的links:
我對他做console.log(links.getBoundingClientRect());
https://ithelp.ithome.com.tw/upload/images/20240407/201354147MenFMftZL.png
結果是這個
{
"x": 24,
"y": 66,
"width": 684,
"height": 201.60000610351562,
"top": 66,
"right": 708,
"bottom": 267.6000061035156,
"left": 24
}

他使用的時機蠻廣的,例如我想做navebar toggle,讓我的linksContainer中可以動態添加links而不需要把高度寫死,這時就可以用 getBoundingClientRect() 方法。取得內部links的高度,然後再使外面 linksContainer的高度等於 links的高度就可以了。
程式碼:

const navToggle=document.querySelector('.nav-toggle');
const linksContainer=document.querySelector('.links-container');
const links=document.querySelector('.links');
navToggle.addEventListener('click',function(){
    // linksContainer.classList.toggle('show-links');
    const containerHeight=linksContainer.getBoundingClientRect().height;
    const linksHeight=links.getBoundingClientRect().height;
    console.log(links.getBoundingClientRect());

    if(containerHeight===0){
        linksContainer.style.height=`${linksHeight}px`;
    }else{
        linksContainer.style.height=0;
    }
})

參考資料:那些被忽略但很好用的 Web API / GetBoundingClientRect
MDN


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

1
davidchen0117
iT邦新手 5 級 ‧ 2024-04-09 09:18:59

使用方式是蠻廣的~~~

我要留言

立即登入留言