How much of an element is visible in viewport

前端 未结 5 1647
天命终不由人
天命终不由人 2020-12-29 09:24

There\'s a div (brown rectangle) on the page. The page is higher than the viewport (orange rectangle) so it can be scrolled, which means that the div

5条回答
  •  盖世英雄少女心
    2020-12-29 10:05

    Chrome now supports Intersection Observer API

    Example (TypeScript):

    export const elementVisibleInPercent = (element: HTMLElement) => {
        return new Promise((resolve, reject) => {
            const observer = new IntersectionObserver((entries: IntersectionObserverEntry[]) => {
                entries.forEach((entry: IntersectionObserverEntry) => {
                    resolve(Math.floor(entry.intersectionRatio * 100));
                    clearTimeout(timeout);
                    observer.disconnect();
                });
            });
    
            observer.observe(element);
            // Probably not needed, but in case something goes wrong.
            const timeout = setTimeout(() => {
                reject();
            }, 500);
        });
    };
    
    const example = document.getElementById('example');
    const percentageVisible = elementVisibleInPercent(example);
    

    Example (JavaScript):

    export const elementVisibleInPercent = (element) => {
        return new Promise((resolve, reject) => {
            const observer = new IntersectionObserver(entries => {
                entries.forEach(entry => {
                    resolve(Math.floor(entry.intersectionRatio * 100));
                    clearTimeout(timeout);
                    observer.disconnect();
                });
            });
    
            observer.observe(element);
            // Probably not needed, but in case something goes wrong.
            const timeout = setTimeout(() => {
                reject();
            }, 500);
        });
    };
    
    const example = document.getElementById('example');
    const percentageVisible = elementVisibleInPercent(example);
    

提交回复
热议问题