![](/img/trans.png)
[英]React Three Fiber, Drei & Intersection Observer: How to change Canvas Model Element Based on The InView Component
[英]How can we specify the time upto which an element should remain on viewport in Intersection Observer
我正在使用Intersection Observer API來檢測出現在視口上的元素。 但我也希望元素應在視口上保持至少 3 秒,然后在此之后檢測到。 我該怎么做? 下面給出的是我正在使用的代碼。
const callBack = (entries) => {
const [entry] = entries;
if (entry.isIntersecting) {
console.log("intersecting");
}
};
const options = {
root: null,
rootMargin: "0px",
threshold: 0.75,
};
useEffect(() => {
const observer = new IntersectionObserver(callBack, options);
if (cardRef.current) {
observer.observe(cardRef.current);
}
return () => {
if (cardRef.current) {
observer.unobserve(cardRef.current);
}
};
}, []);
const callBack = (entries) => {
const [entry] = entries; //объект текущего пересечения элемента
//если пересечение началось и элемент entry.target входит в root
if (entry.isIntersecting) {
//создаём таймер с ууказанием нужной задержки перед срабатыванием
let id = setTimeout(() => {
console.log("intersecting");
}, 3000);
entry.target.start_intersecting_timeout_id = id; //в свойства start_intersecting_timeout_id нашего entry.target элемента записываем id этого таймера
}
//если пересечение началось и элемент entry.target входит в root
//если пересечение началось и элемент entry.target покидает root, или при первом старте не находится в root
else {
//если у нашего entry.target есть свойство start_intersecting_timeout_id
if (entry.target.start_intersecting_timeout_id) {
clearTimeout(entry.target.start_intersecting_timeout_id); //удаляем этот таймаут
delete entry.target.start_intersecting_timeout_id; //удаляем свойство
}
}
//если пересечение началось и элемент entry.target покидает root, или при первом старте не находится в root
}
const options = {
root: null,
rootMargin: "0px",
threshold: 0.75,
}
useEffect(() => {
const observer = new IntersectionObserver(callBack, options);
if (cardRef.current) {
observer.observe(cardRef.current);
}
return () => {
if (cardRef.current) {
observer.unobserve(cardRef.current);
}
};
}, []);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.