【发布时间】:2022-02-10 20:30:11
【问题描述】:
如何使用 JavaScript 检测用户何时滚动到页面上的某个区域?然后运行动画? 我需要在滚动到该部分时运行动画,如果您知道问题的任何部分,请提供帮助。
【问题讨论】:
标签: javascript animation css-animations
如何使用 JavaScript 检测用户何时滚动到页面上的某个区域?然后运行动画? 我需要在滚动到该部分时运行动画,如果您知道问题的任何部分,请提供帮助。
【问题讨论】:
标签: javascript animation css-animations
你可能想看看提供这种功能的 Intersection Observer API。
来自 Intersection Observer MDN 文档 -
Intersection Observer API 提供了一种异步观察的方法 目标元素与祖先的交集的变化 元素或顶级文档的视口。
有关更多信息,请查看 mdn 的关于交叉点观察者 API 的页面 - https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
【讨论】:
您正在寻找IntersectionObserver:
const observer = new IntersectionObserver((nodes)=>{
nodes.forEach(node =>
node.target.classList.toggle('visible', node.isIntersecting)
)
});
observer.observe(document.querySelector('.node'))
.node {
width: 40px;
height: 40px;
background: red;
margin: 500px;
transition: 1s;
display: flex;
justify-content: center;
align-items: center;
}
.node.visible {
background: lightgreen;
border-radius: 50%;
color: white;
}
<div class='node'>x</div>
【讨论】:
如果它不必在 Vanilla Javascript 中,你可以查看这个库 https://greensock.com/scrolltrigger/
【讨论】: