jquery - 在 jQuery 中使用随机数的 div 动态检测页面滚动上的当前 div
问题描述
我有一个包含多个 a4 页面(数字是随机的)的容器,我想检测我当前正在查看的页面。
这是我的代码:
<div class="mycont">
<div id="page1" style="width: 21cm; height:29.7cm; border: 1px solid; margin: 10px 0">
<h1>page1</h1>
</div>
<div id="page2" style="width: 21cm; height:29.7cm; border: 1px solid; margin: 10px 0">
<h1>page2</h1>
</div>
<div id="page3" style="width: 21cm; height:29.7cm; border: 1px solid; margin: 10px 0">
<h1>page3</h1>
</div>
</div>
<div style="position: fixed; bottom: 0; left: 50%; padding: 10px 50px; background-color: #ccc;" id="curpage">cur page 1</div>
有了这个脚本,我只能检测到 1 页
<script>
$(document).ready(function() {
var target = $("#page2").offset().top;
var interval = setInterval(function() {
if ($(window).scrollTop() >= target) {
$("#curpage").text("cur page 2");
}
}, 250);
});
</script>
如何检测页面 3,4... 50,51 等?
解决方案
您可以使用Intersection Observer:
let observer = new IntersectionObserver(function(entries) {
var ele = entries.filter(entry => entry.isIntersecting);
if (ele.length > 0) {
ele = ele[0].target;
console.log('Visible element is now: ' + ele.id);
}
});
document.querySelectorAll('.mycont [id^=page]')
.forEach(ele => observer.observe(ele));
<div class="mycont">
<div id="page1" style="width: 21cm; height:29.7cm; border: 1px solid; margin: 10px 0">
<h1>page1</h1>
</div>
<div id="page2" style="width: 21cm; height:29.7cm; border: 1px solid; margin: 10px 0">
<h1>page2</h1>
</div>
<div id="page3" style="width: 21cm; height:29.7cm; border: 1px solid; margin: 10px 0">
<h1>page3</h1>
</div>
</div>
<div style="position: fixed; bottom: 0; left: 50%; padding: 10px 50px; background-color: #ccc;" id="curpage">cur page 1</div>
推荐阅读
- rundeck - Rundeck - 用户组源插件 - Java 插件类型
- reactjs - 如何在下一个选项卡中打开存储在 Firebase 存储中的 pdf 文件
- xml - xpath 将每个后代拉到嵌套目标标记旁边
- android - 获取任何视频的纵横比
- c++ - C ++:围绕原点旋转点,但输出点在一定程度上不正确
- c# - C# RestClient 调用 magento api 返回 401 签名无效
- ios - 如何在 iOS 中创建添加新联系人,例如 whatsapp
- java - 从 Java 中的 ArrayList 中获取 names()
- linux - 使用 mailx 发送邮件正文和附件 - Linux
- r - 在 R 中使用 igraph 计算属性类之间的网络统计信息