Javascript 轻松获得元素大小、位置的实用方法| getBoundingClientRect()

返回值是一个DOMRect物件,用px 为单位描述这个矩形的位置跟大小。
其中包含x/y/width/height/top/right/bottom/left 等属性。

width :元素的 borderBox 度,相于 offsetwidth

height : 元素的 borderBox 高度,相于 offsetHeight

x: 元素的 borderBox 左上角相于视窗的水平(X)座槽

y:元素的 borderBox 左上角相于视窗的垂直(Y)座槽

left : 元素的 borderBox 左上角相于视窗的水平(X)座,等同 x

top:元素的 borderBox 左上角相于视窗的垂直(Y)座,等同 y

right: 元素的 borderBox 右下角相于视窗的水平(X)座槽

bottom :元素的 borderBox 右下角相于视窗的垂直(Y)座

然后注意他的宽跟高是有包含border宽度的;而位置属性则是从viewport(视窗)的左上角开始算。

例如下面是我测量我的nav的links:
我对他做console.log(links.getBoundingClientRect());

结果是这个
{
"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;
    }
})

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值