JavaScript getBoundingClientRect() 获取元素尺寸和位置
除了获取元素的宽高,getBoundingClientRect() 还能获取元素相对于视口左上角的位置、元素的右下角位置等信息。这些信息可以通过返回的 DOMRect 对象中的属性进行访问,例如:
width:元素的宽度height:元素的高度top:元素顶部相对于视口的距离bottom:元素底部相对于视口的距离left:元素左侧相对于视口的距离right:元素右侧相对于视口的距离
使用方法示例:
const rect = document.querySelector('.box').getBoundingClientRect();
console.log(rect.width);
console.log(rect.height);
console.log(rect.top);
console.log(rect.bottom);
console.log(rect.left);
console.log(rect.right);
原文地址: https://www.cveoy.top/t/topic/mtbP 著作权归作者所有。请勿转载和采集!