>[danger]介绍一下Js中的getBoundingClientRect `getBoundingClientRect()` 是一个用于获取元素位置和尺寸信息的方法。它返回一个 DOMRect对象,其提供了元素的大小及其相对于视口的位置,其中包含了以下属性: * `x`:元素左边界相对于视口的 x 坐标。 * `y`:元素上边界相对于视口的 y 坐标。 * `width`:元素的宽度。 * `height`:元素的高度。 * `top`:元素上边界相对于视口顶部的距离。 * `right`:元素右边界相对于视口左侧的距离。 * `bottom`:元素下边界相对于视口顶部的距离。 * `left`:元素左边界相对于视口左侧的距离。 ``` const box = document.getElementById('box'); const rect = box.getBoundingClientRect(); console.log(rect.x); // 元素左边界相对于视口的 x 坐标 console.log(rect.y); // 元素上边界相对于视口的 y 坐标 console.log(rect.width); // 元素的宽度 console.log(rect.height); // 元素的高度 console.log(rect.top); // 元素上边界相对于视口顶部的距离 console.log(rect.right); // 元素右边界相对于视口左侧的距离 console.log(rect.bottom); // 元素下边界相对于视口顶部的距离 console.log(rect.left); // 元素左边界相对于视口左侧的距离 ``` 为了更好地理解,我在页面上设置了一个容器,其对应属性看下图: ![](https://img.kancloud.cn/22/b2/22b26f4087c83d2bd19d566b844c52c9_801x502.png) >[info]应用场景 这个方法通常用于需要获取元素在视口中的位置和尺寸信息的场景,比如实现拖拽、定位或响应式布局等,兼容性很好,一般用滚动事件比较多。 特殊场景会用上,比如你登录了淘宝的网页,当你下拉滑块的时候,下面的图片不会立即加载出来,有一个懒加载的效果。当上面一张图片没在可视区内时,就开始加载下面的图片。 下面代码就是判断一个容器是否出现在可视窗口内: ``` const box = document.getElementById('box') window.onscroll = function () {//window.addEventListener('scroll',()=>{}) console.log(checkInView(box)); } function checkInView(dom) { const { top, left, bottom, right } = dom.getBoundingClientRect(); return top > 0 && left > 0 && bottom <= (window.innerHeight || document.documentElement.clientHeight) && right <= (window.innerWidth || document.documentElement.clientWidth) } ``` 当容器在可视区域内就输出`true`,否则就是`false`。