如何在每次滚动页面时触发动画?

How to make an animation trigger each time the page is scrolled?

我有一个非常转租的关键帧动画。我希望它在每次滚动页面时播放 - 而不是在进入视点时播放一次。每次触摸卷轴。我只能在视口中找到 运行 一次 - 这很好,但每次在视口中触摸滚动时都需要播放。有什么想法吗?

/* CSS */
.aha-section .pixels .light {
    margin-top: 4px;
    margin-left: 33px;
    animation: slide 2s 1;
}

@keyframes slide {
    from {
        margin-left: 33px;
    }
    50% {
        margin-left: 45px;
    }
    to {
        margin-left: 33px;
    }
}

您将需要使用一些 JavaScript...然后您将收听 scroll 事件以执行所需的功能...

要触发动画,请为其设置 class:

.scrolled .aha-section .pixels .light {
    animation: slide 2s 1;
} 

并让 javascript 在事件 scroll 发生时添加此 class:

document.body.className += ' scrolled';

希望它能帮助你指明方向。

let animated = false;

window.addEventListener("scroll", (event) => {
    animateOnScroll();
});

function animateOnScroll(){
  if(animated == false){
    animated = !animated;
    document.body.className += ' scrolled';  
    setTimeout(function() {
        animated = false;
        document.body.classList.remove('scrolled');
    }, 2000); //match whatever time set on css animation 
  }
}
.aha-section {
  position: fixed;
}
.aha-section .pixels .light {
    margin-top: 4px;
    margin-left: 33px;
}

.scrolled .aha-section .pixels .light {
    animation: slide 2s 1;
}

@keyframes slide {
    from {
        margin-left: 33px;
    }
    50% {
        margin-left: 45px;
    }
    to {
        margin-left: 33px;
    }
}

.scroll-emulator {
  height: 2500px;
}
<div class="aha-section">
    <div class="pixels">
        <div class="light">Light</div>
    </div>
</div>
<div class="scroll-emulator"><div>