簡體   English   中英

Intersection Observer 不是在視口上的可見性低於 50% 的工作元素

[英]Intersection Observer isn't working elements having less than 50% visibility on viewport

我添加了一個 Intersection Observer 用於圖像延遲加載。 但是由於某種原因,如果視口上的div元素的可見性小於 50%,則 Intersection Observer 不會加載圖像。

我想加載圖像,即使它在視口上顯示為 0% 到 100%。 這是我的 IntersectionObserver 實例:

import {useEffect} from "react";
let listenerCallbacks = new WeakMap();
let observer;

function handleIntersections(entries) {
    entries.forEach(entry => {
        if (listenerCallbacks.has(entry.target)) {
            let cb = listenerCallbacks.get(entry.target);

            if (entry.isIntersecting || entry.intersectionRatio > 0) {
                observer.unobserve(entry.target);
                listenerCallbacks.delete(entry.target);
                cb();
            }
        }
    });
}

function getIntersectionObserver() {
    if (observer === undefined) {
        observer = new IntersectionObserver(handleIntersections, {
            root: null,
            rootMargin: "0px",
            threshold: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
        });
    }
    return observer;
}

export function useIntersection(elem, callback) {
    useEffect(() => {
        let target = elem.current;
        let observer = getIntersectionObserver();
        listenerCallbacks.set(target, callback);
        observer.observe(target);

        return () => {
            listenerCallbacks.delete(target);
            observer.unobserve(target);
        };
    }, []);
}

當前結果:

結果片段---

我想要的是:

我想要什么——

threshold: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]會在每次可見性再超過 10% 時運行回調,所以你會過度獲取。

由於您想在div的一小部分可見時立即獲取,因此將threshold設置為 0,例如threshold:0 ,並將您的if語句在handleIntersections中更改為:

if (entry.isIntersecting) 

最后,它還與您滾動的速度、后端的響應速度以及圖像的大小有關。

參考mdn

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM