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;
};
方法三:使用 IntersectionObserver
对象(性能最佳,推荐使用)
- IntersectionObserver 的原理基于浏览器的布局引擎和事件循环机制。它通过浏览器内部的优化机制来高效地检测元素与其祖先元素(或视口)之间的交叉状态变化
- 以下是 React 使用例子
import React, { useRef, useLayoutEffect, useState } from "react";
const MyComponent = () => {
const [isVisible, setIsVisible] = useState(false);
const bottomRef = useRef<HTMLDivElement | null>(null);
useLayoutEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting) {
setIsVisible(true);
} else {
setIsVisible(false);
}
},
{
root: null,
rootMargin: "0px",
threshold: 0.1,
}
);
if (bottomRef.current) {
observer.observe(bottomRef.current);
}
return () => {
if (bottomRef.current) {
observer.unobserve(bottomRef.current);
}
};
}, []);
return (
<div>
<div style={{ position: "fixed", top: "40vh", left: 0, width: '100vw', textAlign: 'center' }}>
{isVisible ? "Element is in view" : "Element is out of view"}
</div>
<div style={{ height: "150vh" }}>Scroll down to see the element</div>
<div
ref={bottomRef}
style={{ height: "100px", backgroundColor: "lightblue" }}
/>
</div>
);
};
export default MyComponent;