简体   繁体   中英

How to tell what fraction of element is inside viewport?

How to determine what percentage of a DOM element is inside the current viewport ? I want to calculate the ratio of area of element inside viewport and the total area of the element.

Related question: How to tell if a DOM element is visible in the current viewport?

See getBoundingClientRect and Window.innerHeight .

let {top, height} = element.getBoundingClientRect(),
    percentVisible = Math.max(0, Math.min(1, (window.innerHeight - top) / height));

I'm guessing at your use case, but in modern browsers, see IntersectionObserver and its intersectionRatio .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM