在js中getBoundingClientRect有什么作用?

这篇文章主要介绍了js中getboundingclientrect的作用及兼容方案详解,现在分享给大家,也给大家做个参考。

1、getBoundingClientRect的作用

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

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

getBoundingClientRect()

这个方法返回一个矩形对象,包含四个属性:left、top、right和bottom。分别表示元素各边与页面上边和左边的距离。

  1. var box=document.getElementById('box'); // 获取元素alert(box.getBoundingClientRect().top); // 元素上边距离页面上边的距离alert(box.getBoundingClientRect().right); // 元素右边距离页面左边的距离alert(box.getBoundingClientRect().bottom); // 元素下边距离页面上边的距离alert(box.getBoundingClientRect().left); // 元素左边距离页面左边的距离

登录后复制

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

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

看图:

 在js中getBoundingClientRect有什么作用?

3. 浏览器兼容性

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

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

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

  1. 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);

登录后复制

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

JS中Number类型(详细教程)

JS中Number类型(详细教程)

JS中Number类型(详细教程)

以上就是在js中getBoundingClientRect有什么作用?的详细内容,更多请关注【创想鸟】其它相关文章!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
编程技术

JS做出数组遍历方式汇总以及性能对比

2025-3-31 22:57:09

编程技术

jQuery做出合并/追加数组除重功能

2025-3-31 22:57:18

0 条回复 A文章作者 M管理员
欢迎您,新朋友,感谢参与互动!
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
私信列表
搜索