![](/img/trans.png)
[英]How to check if element is half visible in the viewport with JavaScript?
[英]How to check if lowest part of div is visible in viewport?
检查 div 的最低部分是否在视口中可见的公式是什么? 滚动 div 时,上半部分是可见的还是隐藏的并不重要
您可以使用IntersectionObserver来识别屏幕上是否有内容。 如果您制作一个占位符并将其磁化到父 div 的底部,那么您就可以使其成为可能。
但是,如果您不想使用 IntersectionObserver API,您可以尝试 getBoundingClientRect() + window.innerHeight ,如下所示:
const targetEl = document.querySelector('#target'); const windowsHeight = window.innerHeight; // I heartily recommend to use some kind of throttling (lo-dash.throttle) here to reduce amount of callback executions document.addEventListener('scroll', () => { const bottom = targetEl.getBoundingClientRect().bottom; if (windowsHeight > bottom) { console.log('bottom is visible'); } else { console.log('bottom is hidden'); } })
/* All css are just for the demo, you only need a JS code */ body { padding: 300px 20px; } #target { height: 2000px; width: 100%; background-color: gray; }
<div id="target"> content here </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.