通过滚动触发 CSS 关键帧动画 [英] Trigger a CSS keyframe animation via scroll

查看:87
本文介绍了通过滚动触发 CSS 关键帧动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有动画的元素:

Say I have an element with an animation:

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

@keyframes Fade {
  /* do stuff */
}

如何仅在用户向下滚动时触发此动画?Vanilla JS、jQuery、ScrollMagic、GSAP/TweenMax,随心所欲.

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

添加动画属性本身会触发效果吗?因此,用户滚动到某个点/元素,然后我应用如下内容: $('#element').css('animation', 'Fade 3s linear 1s forwards');?

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

推荐答案

当用户向下滚动时,向具有动画的元素添加一个类.

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

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

演示

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

这篇关于通过滚动触发 CSS 关键帧动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆