getBoundingClientRect方法简介

1.getBoundingClientRect方法简介

getBoundingClientRect 返回的是一个 DOMRect 对象,是一组矩形集合,我们这次所使用的返回值主要是left、top、bottom和right。其余的返回值width、height、x、y这次用不到,就不再讨论。

使用方法如下:

let domToTop = dom.getBoundingClientRect().top // dom 的顶边到视口顶部的距离
let domToLeft = dom.getBoundingClientRect().left // dom 的左边到视口左边的距离
let domToBottom = dom.getBoundingClientRect().bottom // dom 的底边到视口顶部的距离
let domToRight = dom.getBoundingClientRect().right // dom 的右边到视口左边的距离
注意事项:
得到的值是相对于视口而言的,即如果页面的滚动位置发生变化,那么得到的top、left也会发生变化;如果需要计算到body边框的距离,需要再加上网页滚动条的长度。下面会给出完整例子。
这个方法返回的四个值都是相对于当前视口的左上角而言的。即top和bottom是dom的顶边和底边到视口的顶部的距离,同理left和right是相对于视口左边的距离。
scrolltop 和 offsettop 是距离父元素的。

posted @ 2020-04-16 16:55  Action_swt  阅读(1931)  评论(0编辑  收藏  举报