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

时间:2021-05-20 20:53:17

标签: css animation scroll css-animations

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

/* 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;
    }
}

1 个答案:

答案 0 :(得分:1)

您将需要使用一些 JavaScript...然后您将监听 minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive) 事件以执行所需的功能...

要触发动画,请为其设置一个类:

scroll

并在事件 .scrolled .aha-section .pixels .light { animation: slide 2s 1; } 发生时让 javascript 添加此类:

scroll

希望能帮助你指明方向。

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;
}