html检测指定位置元素,js中getBoundingClientRect获取某个html元素相对于视窗的位置...

本文介绍了如何使用原生JavaScript的getBoundingClientRect方法来获取HTML元素相对于视口的位置,该方法返回一个对象,包含top、right、bottom、left、width和height等属性。在IE5以上浏览器中均支持,但在IE6、7中需要修正left和top的偏移值。通过提供的示例函数getObjXy,可以获取元素的精确位置信息,适用于需要精确布局和定位的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用习惯了jQuery的人,一般会用offset().top来获取元素相对于窗口的位置,其实我们还有一个原生的更好用的方法:getBoundingClientRect

1.getBoundingClientRect的作用

getBoundingClientRect用于获取某个html元素相对于视窗的位置集合。

执行 object.getBoundingClientRect();会得到元素的top、right、bottom、left、width、height属性,这些属性以一个对象的方式返回。

document.querySelector('.test').getBoundingClientRect()

得到如下信息:

32e4092a473bb2ea979455f6f0774d77.png

2.getBoundingClientRect上下左右属性值解释

主要是left和bottom要解释一下,left是指右边到页面最左边的距离,bottom是指底边到页面顶边的距离。

fe4e04c6a3d5367daee03013ada6ed36.png

3.浏览器兼容性

ie5以上都能支持,但是又一点点地方需要修正一下,

IE67的left、top会少2px,并且没有width、height属性。

4.利用getBoundingClientRect来写一个获取html元素相对于视窗的位置集合的方法

function getObjXy(obj){

var xy = obj.getBoundingClientRect();

var top = xy.top-document.documentElement.clientTop+document.documentElement.scrollTop,//document.documentElement.clientTop 在IE67中始终为2,其他高级点的浏览器为0

bottom = xy.bottom,

left = xy.left-document.documentElement.clientLeft+document.documentElement.scrollLeft,//document.documentElement.clientLeft 在IE67中始终为2,其他高级点的浏览器为0

right = xy.right,

width = xy.width||right - left, //IE67不存在width 使用right - left获得

height = xy.height||bottom - top;

return {

top:top,

right:right,

bottom:bottom,

left:left,

width:width,

height:height

}

}

var test = getObjXy(document.getElementById('test'));

alert("top:" + test.top + ", right:" + test.right + ", bottom:" + test.bottom + ", left:" + test.left);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值