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);     // 元素左边界相对于视口左侧的距离
复制代码

这个方法通常用于需要获取元素在视口中的位置和尺寸信息的场景,比如实现拖拽、定位或响应式布局等,兼容性很好,一般用滚动事件比较多。

特殊场景会用上,比如你登录了淘宝的网页,当你下拉滑块的时候,下面的图片不会立即加载出来,有一个懒加载的效果。当上面一张图片没在可视区内时,就开始加载下面的图片。

下面代码就是判断一个容器是否出现在可视窗口内:

1
2
3
4
5
6
7
8
9
10
11
12
13
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)
        }

 摘抄https://www.kancloud.cn/hanxuming/interview/3173354 

posted @   三寸日光  阅读(68)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2020-09-23 nginx跨域配置
点击右上角即可分享
微信分享提示