
监测元素滚动位置的 javascript 代码
如何在滑动页面时检测某个段落何时与页面可视区域顶部接触?
html 代码
<body>
<div>
<!-- 一个段落开始 -->
<div dh="a">a</div>
<ul h="a">
<li>...</li>
...
</ul>
<!-- 一个段落结束 -->
<div dh="b">b</div>
<ul h="b">
<li>...</li>
...
</ul>
....
<div dh="z">z</div>
<ul h="z">
<li>...</li>
...
</ul>
</div>
</body>javascript 代码
立即学习“Java免费学习笔记(深入)”;
通过 window.scroll 事件侦测元素滚动位置,当目标元素的顶部与页面可视区域顶部接触时触发事件。以下是如何实现的代码:
const paragraphs = document.querySelectorAll('div[dh]');
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
console.log('entry', `${entry.target.getAttribute('dh')}`, entry.boundingClientRect.y);
});
});
paragraphs.forEach((paragraph) => {
observer.observe(paragraph);
});说明
以上就是如何使用 JavaScript 代码在页面滚动时实时监测某个特定段落何时与页面可视区域顶部接触?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号