<分区>
标签 javascript jquery html css
<分区>
example 我正在尝试制作这样的网络。而且我不知道如何在用户向下滚动页面时产生效果。并且部分的背景变得更长。如何知道用户是否向下滚动并且元素对用户可见。 我的问题很像 this.
最佳答案
在使用第 3 方库之前,我会看一下 Intersection Observer .
The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.
Support在 Safari 之外非常好,尽管有一个 polyfill .我通常不提倡使用 polyfill,除非被 polyfill 的功能大大简化了 Web 开发。在这种情况下,我认为 Intersection Observer 值得 polyfill。在 Observer 之前,创建具有许多滚动点交叉事件的复杂应用程序需要跳过的障碍是一个巨大的失败。
这是取自 here 的演示.
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 - 如何知道一个元素是否对用户可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54088827/