如何检测用户何时使用JavaScript滚动到页面上的某个区域?然后运行动画



如何检测用户何时使用JavaScript滚动到页面上的某个区域?然后运行动画?当滚动到那个部分时,我需要运行动画。如果你知道问题的任何部分,请帮忙。

您正在寻找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>

u可能想看看交集观察者API,它提供了这种能力。

来自交叉口观察员MDN文件-

交叉点观察者API提供了一种异步观察的方法目标元素与祖先相交处的变化元素或顶级文档的视口。

有关更多信息,请查看mdn关于交叉点观察员API的页面-https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

如果它不必在Vanilla Javascript中,你可以看看这个库https://greensock.com/scrolltrigger/

最新更新