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
.
上一篇: jquery检查元素在视口中是否可见
下一篇: 如何判断元素的哪一部分在视口内?