javascript - 如何知道元素是否对用户可见?
解决方案
在使用 3rd 方库之前,我会看一下Intersection Observer。
Intersection Observer API 提供了一种异步观察目标元素与祖先元素或顶级文档视口的交集变化的方法。
Safari 之外的支持非常好,尽管有一个polyfill。我通常不提倡使用 polyfill,除非被 polyfill 的特性极大地简化了 Web 开发。在这种情况下,我认为 Intersection Observer值得使用 polyfill。在 Observer 之前,创建一个包含许多滚动点相交事件的复杂应用程序需要跳过的环节是一个巨大的麻烦。
这是从这里获取的演示。
var statusBox = document.getElementById("statusBox");
var statusText = document.getElementById("statusText");
function handler(entries, observer) {
for (entry of entries) {
statusText.textContent = entry.isIntersecting;
if (entry.isIntersecting) {
statusBox.className = "yes";
} else {
statusBox.className = "no";
}
}
}
/* By default, invokes the handler whenever:
1. Any part of the target enters the viewport
2. The last part of the target leaves the viewport */
let observer = new IntersectionObserver(handler);
observer.observe(document.getElementById("target"));
html {
height: 200%;
min-height: 400px;
text-align: center;
font-family: sans-serif;
padding-top: 3.5em;
}
#viewport {
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
color: #aaa;
font-weight: bold;
font-size: 20vh;
border: 8px dashed #aaa;
padding-top: 40vh;
margin: 0;
user-select: none;
cursor: default;
}
#target {
background-color: #08f;
display: inline-block;
margin: 100vh auto 100vh;
color: white;
padding: 4em 3em;
position: relative;
}
#statusBox {
position: fixed;
top: 0;
left: 1em;
right: 1em;
font-family: monospace;
padding: 0.5em;
background-color: #ff8;
border: 3px solid #cc5;
opacity: .9;
}
#statusBox.yes {
background: #8f8;
border-color: #5c5;
}
#statusBox.no {
background: #f88;
border-color: #c55;
}
<p id="viewport">Viewport</p>
<p>Scroll down...<p>
<div id="target">Target</div>
<p id="statusBox">
isIntersecting ===
<span id="statusText">unknown</span>
</p>
推荐阅读
- javascript - 导出函数中的返回语句在 Node JS 中返回“未定义”,同时使用 aws-sdk 和 express
- javascript - 此脚本未运行,是否缺少功能?
- python - Heroku 使用 sqlite 部署 Django 应用程序
- inertiajs - 未知的自定义元素:
- 您是否正确注册了组件?对于递归组件,请确保提供“名称” - wpf - Xamarin 绑定在 Behavior<> 中不起作用
- python - 通过匹配键和值从 MongoDB 获取文档
- ios - 在核心数据中存储钥匙串密钥?
- css - 如何在 Google Blogger 中使用“document.querySelector”?
- javascript - 无法从expo react native中的url将图像下载到本地目录
- python - 如何提高pytesseract的准确率?