祝你一切顺利。我有一段javascript代码,工作得很好,只有当用户向下滚动并且元素进入视口时,动画才开始播放。然而,动画只播放一次。我如何使动画重新开始每次用户滚动,他们进入视窗?提前谢谢你。
这是迄今为止我所拥有的JavaScript代码,当动画第一次进入视口时,只触发动画一次。
var observer = new IntersectionObserver(function(entries) {
entries.forEach(function(element) {
if(element.isIntersecting === true){
element.target.classList.add("play-animation");
/*
* optional: By callsing the 'unobserve' the element gets removed from the observer
* (by doing this, if the element is scrolled out of view and back into view after, nothing will happenn)
*/
observer.unobserve(element.target);
}
});
}, { threshold: [0] });
observer.observe(document.querySelector('.progress-ai'));
observer.observe(document.querySelector('.progress-dw'));
observer.observe(document.querySelector('.progress-ps'));
observer.observe(document.querySelector('.progress-ae'));
observer.observe(document.querySelector('.progress-xd'));
observer.observe(document.querySelector('.progress-id'));
不要在元素离开视图时观察它们。相反,添加一个else
语句,当元素与不相交时,动画类就会被移除。
const observer = new IntersectionObserver(function(entries) {
entries.forEach(function(element) {
if(element.isIntersecting === true) {
element.target.classList.add("play-animation");
} else {
element.target.classList.remove("play-animation");
}
});
}, { threshold: [0] });
const elements = document.querySelectorAll('.progress-ai, .progress-dw, .progress-ps, .progress-ae, .progress-xd, .progress-id');
for (const element of elements) {
observer.observe(element);
}