如何使用Jquery在滚动时触发CSS @keyframe动画?

时间:2018-05-01 19:10:11

标签: jquery html css sass

  1. 首先,我在使用box滚动动画这些jquery元素时遇到一些麻烦。当我滚动过animation的1/4时,我希望我的section开始。
    1. 其次,我的box div曾经是垂直居中的,但在转换过程中添加@keyframes后,它们不再居中。如果您删除了animation-fill-mode: forwards,则可以看到它们在转换结束时如何重新启动。
    2. 最后一个问题..当我开始滚动而不必为每个jquery编写不同的代码时,sections可以用来为这两个框添加动画效果吗?我想如果我在我的box div中添加一些应该有用的公共类,对吗?
  2. 最初,在我的jquery文件中,我尝试在hidden div上设置opacity:0box,当我开始滚动时,它会变为showing 1}}带有opacity:1的课程..但是并没有那么顺利。

    在YouTube上找到的其他解决方案也没有帮助。将其他人代码与我的混合似乎并不能很好地运作。

    正如你所看到的那样,没有jquery代码,因为在我的大脑开始弄乱它之后它是一团糟,有一次我认为我应该重新开始。

    Here是指向我的Codepen的链接。

    .landing-page
    .section-one
      .box-one
    .section-two
      .box-two
    

    SASS

    @mixin box()
      position: absolute
      width: 200px
      height: 200px
      background: black
    .landing-page
      height: 100vh
      width: 100vw
      background: gray
    .section-one
      position: relative
      height: 100vh
      width: 100vw
      background: lightblue
      .box-one
        @include box()
        top: 50%
        right: 10%
        transform: translate(-50%,-50%)
        animation-name: box-one-animation
        animation-duration: 2s
        animation-fill-mode: forwards
    .section-two
      position: relative
      height: 100vh
      width: 100vw
      background: lightgreen
      .box-two
        @include box()
        top: 50%
        left: 10%
        transform: translate(-50%,-50%)
        animation-name: box-two-animation
        animation-duration: 2s
        animation-fill-mode: forwards
    
    @keyframes box-one-animation
      0%
        transform: translateX(0)  
      100%
        transform: translateX(-50%)
    @keyframes box-two-animation
      0%
        transform: translateX(0)  
      100%
        transform: translateX(50%)  
    

1 个答案:

答案 0 :(得分:0)

首先,您需要为滚动事件设置一些事件侦听器,这样您就可以基于scrollPos触发动画,或者可能是偏移到顶部的元素。

以下是事件监听器:

https://developer.mozilla.org/en-US/docs/Web/Events/scroll

var last_known_scroll_position = 0;
var ticking = false;

function doSomething(scroll_pos) {
  // do something with the scroll position
  console.log(scroll_pos);
  if(scroll_pos > 200){
    console.log(document.getElementsByClassName('box-one')[0].classList);
     document.getElementsByClassName('box-one')[0].classList.add('animate-me');
  }
}

window.addEventListener('scroll', function(e) {
  last_known_scroll_position = window.scrollY;
  if (!ticking) {
    window.requestAnimationFrame(function() {
      doSomething(last_known_scroll_position);
      ticking = false;
    });
    ticking = true;
  }
});

查看doSomething功能,您可以在此处定义偏移或决定整体方法。对于css部分,只需弹出一个类,在该类上引用动画来触发动画。

笔在这里:https://codepen.io/cidicles/pen/gzWwEz

有很多伟大的图书馆可以为你做这些类型的动画,比如Scroll Magic或Skrollr,但是构建你自己的动画总是很有趣:p。

https://github.com/Prinzhorn/skrollr
http://scrollmagic.io/