Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...