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

查看:165
本文介绍了通过滚动触发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 forward');

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天全站免登陆