JS如何判断一个元素是否在可视区域中?下文分解。
方法一:利用 scrollTop
、offsetTop
、clientHeight
的关系
export const isInViewPort = element => {
const clientHeight =
window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
const offsetTop = element.offsetTop;
const scrollTop = document.documentElement.scrollTop;
return offsetTop <= clientHeight + scrollTop;
};
方法二:通过getBoundingClientRect的top、left、right、bottom属性判断元素的位置是否在可视区域
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;
};