返回值是一个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;
}
})