当前位置:   article > 正文

JS判断一个元素是否在可视区域中

JS判断一个元素是否在可视区域中

JS如何判断一个元素是否在可视区域中?下文分解。

方法一:利用 scrollTopoffsetTopclientHeight 的关系

/**
 * 利用 offsetTop <= clientHeight + scrollTop;
 * @param element
 * @returns
 */
export const isInViewPort = element => {
  // clientHeight 兼容所有浏览器写法
  const clientHeight =
    window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
  const offsetTop = element.offsetTop;
  const scrollTop = document.documentElement.scrollTop;
  return offsetTop <= clientHeight + scrollTop;
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

方法二:通过getBoundingClientRect的top、left、right、bottom属性判断元素的位置是否在可视区域

/**
 * 通过getBoundingClientRect的top、left、right、bottom属性判断元素的位置是否在可视区域
 * @param element
 * @returns
 */
export const isInViewPort = element => {
  const viewWidth =
    window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  const viewHeight =
    window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

  const { top, right, bottom, left } = element.getBoundingClientRect();

  return top >= 0 && left >= 0 && right <= viewWidth && bottom <= viewHeight;
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号