Trigger a CSS keyframe animation via scroll

2019-04-14 15:25发布

问题:

Say I have an element with an animation:

#element {
  animation: Fade 3s linear 1s forwards;
}

@keyframes Fade {
  /* do stuff */
}

How can I trigger this animation only when the user scrolls down? Vanilla JS, jQuery, ScrollMagic, GSAP/TweenMax, however you want to do it.

Would adding the animation property itself trigger the effect? So, a user scrolls to a certain point/element, and then I apply something like: $('#element').css('animation', 'Fade 3s linear 1s forwards');?

回答1:

Add a class to element that has the animation on it when the user scrolls down.

Pseudocode

on window scroll {
  if (scroll pos > x) {
    element.addclass("animateMe");
  }
}

Demo

http://jsbin.com/zuqexigepe/edit?html,output

If you want the animation to happen every time the user scrolls past a certain point, you can simply change the scroll event to remove the class as well, like so:

$(window).scroll(function () {
  if($(window).scrollTop() > 0) {
    element.addClass("animateMe");
  }
  else {
    element.removeClass("animateMe");
  }
});