Appearance
如何判断一个元素在视口内
使用元素位置判断
js
const isVisible = (el) => {
const rect = el.getBoundingClientRect();
const height = window.innerHeight || document.documentElement.clientHeight;
return height >= rect.top;
};
const isVisible = (el) => {
const rect = el.getBoundingClientRect();
const height = window.innerHeight || document.documentElement.clientHeight;
return height >= rect.top;
};
IntersectionObserver
js
let observer = new IntersectionObserver(
(entries, self) => {
entries.forEach((entry) => {
// 如果元素出现在视口内
if (entry.isIntersecting) {
}
});
},
{
rootMargin: "0px",
threshold: 0,
}
);
// 观察元素
observer.observe(el);
let observer = new IntersectionObserver(
(entries, self) => {
entries.forEach((entry) => {
// 如果元素出现在视口内
if (entry.isIntersecting) {
}
});
},
{
rootMargin: "0px",
threshold: 0,
}
);
// 观察元素
observer.observe(el);