如何判断元素是否在可视区域内--getBoundingClientRect

介绍

Element.getBoundingClientRect()方法返回元素的大小及其相对于视口的位置。

根据MDN文档 getBoundingClientRect 方法返回的是一个DOMRect对象

DOMRect 对象包含了一组用于描述边框的只读属性left、top、right、bottom、x、y以及width、height,单位为像素。

属性 描述
bottom Y 轴,相对于视口原点(viewport origin)矩形盒子的底部。只读
height 矩形盒子的高度(等同于 bottom 减 top)。只读
left X 轴,相对于视口原点(viewport origin)矩形盒子的左侧。只读
right X 轴,相对于视口原点(viewport origin)矩形盒子的右侧。只读
top Y 轴,相对于视口原点(viewport origin)矩形盒子的顶部。只读
width 矩形盒子的宽度(等同于 right 减 left)。只读
x X 轴,相对于视口原点(viewport origin)矩形盒子的左侧。只读
y Y 轴,相对于视口原点(viewport origin)矩形盒子的顶部。只读

除了 width 和 height 外的属性都是相对于视口的左上角位置而言的。

*该对象的width和 height 值包含元素的 border 和 padding。

元素的offsetWidth包含 border、 padding、content的宽度。
元素的clientWidth仅包含元素的 padding、content的宽度。

判断元素是否在视窗内

根据该对象返回值可以通过以下条件判断元素是否在可视范围内:

当 DOMRect.top 小于视口高度 且 DOmRect.bottom 大于0

当 DOMRect.left 小于视口宽度 且 DOmRect.right 大于0

function elementInView(element) {
  const rect = element.getBoundingClientRect()

  const yInView = rect.top < window.innerHeight && rect.bottom > 0

  const xInView = rect.left < window.innerWidth && rect.right > 0

  return yInView && xInView
}

window.inner[Width|Height] 在Chrome、Firefox下均不包含滚动条,而Edge、IE浏览器下则包含滚动条

猜你喜欢

转载自www.cnblogs.com/zzy1996/p/11568234.html
今日推荐