Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

javascript - Trigger a CSS keyframe animation via scroll

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');?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...