js中getBoundingClientRect()方法详解

getBoundingClientRect()方法用于获取元素在浏览器视窗中的位置信息。该方法没有参数,调用方式为element.getBoundingClientRect(),其中element是要获取位置的DOM元素。

getBoundingClientRect()返回一个包含6个属性的Object对象:top, left, right, bottom, width, height。

  • top: 元素上边到视窗上边的距离
  • right: 元素右边到视窗左边的距离
  • bottom:元素下边到视窗上边的距离
  • left:元素左边到视窗左边的距离
  • width:元素自身的宽度
  • height:元素自身的高度

例如,如果需要获取id为box的元素的位置信息,可以使用以下代码:

var element = document.getElementById('box');
var rectObject = element.getBoundingClientRect();

对于兼容性,getBoundingClientRect()方法在IE5及以上版本都支持。

转载

posted @ 2023-06-28 10:12  he_duanlong  阅读(84)  评论(0)    收藏  举报