如何使用Waypoints.js在Scroll上触发动画

时间:2015-02-18 20:33:42

标签: javascript jquery animation jquery-waypoints inview

我一直试图弄清楚如何在滚动时触发动画,而我却无法理解。基本上,我希望有一个类可以添加到我的标题中,只要带有类的元素滚动到视图中,它就会触发动画。

我尝试使用jQuery Inview插件,但我无法按照自己的意愿去做。然后我切换到Waypoints.js并且我有点工作,但它并不完美。现在,当我第一次滚动它们时,元素会生成动画,但当我向上和向下滚动页面时它们什么也不做。动画只会发射一次。

以下是我目前的代码。如果有人可以帮助我找出一种方法来让每次用户滚过它们时触发动画 - 并且还有一种方法来压缩代码,使其基于类而不是ID激发 - 这将是非常好的。 (现在,我对每个元素都有单独的功能。)

PS:我使用animate.csswow.jstextillate.js制作动画。

HTML

<h1 class="lettering wow fadeInDown" id="l1" data-in-effect="flipInY">Yo. Check it out.</h1>

的jQuery

$(function () {
var l1 = $("#l1");
var waypoint = new Waypoint({
  element: document.getElementById('l1'),
  handler: function() {
      l1.textillate({ in: { effect: 'flipInY' } });
  },
  offset: 'bottom-in-view',
});
});

感谢您的帮助!

编辑:我找到了一个部分解决方案,每次滚过它们时都会触发动画。但是,我似乎只能将它与ids一起使用。我宁愿能够定位class而不是为每个新标题编写单独的函数。有关如何修改以下代码以使其适用于.lettering类的任何想法吗?

// Animate #l1
$(function () {
var animatel1 = $('#l1').textillate({ 
    autoStart: false,
    in: { effect: 'flipInY' },
    out: { effect: 'fadeOut', sync: true, }
});

var l1 = $("#l1");
var inview = new Waypoint.Inview({
  element: $('#l1'),
  enter: function(direction) {
  },
  entered: function(direction) {
    animatel1.textillate('in')
  },
  exit: function(direction) {
    animatel1.textillate('out')
  },
  exited: function(direction) {
  }
})  
});

2 个答案:

答案 0 :(得分:1)

让它与类一起工作是循环遍历元素数组的问题。我看到你正在使用jQuery,所以它可以帮助你找到一些样板:

$(function () {
  $('.your-class').textillate({ 
      autoStart: false,
      in: { effect: 'flipInY' },
      out: { effect: 'fadeOut', sync: true, }
  });

  $('.your-class').each(function() {
    new Waypoint.Inview({
      element: this,
      entered: function(direction) {
        $(this.element).textillate('in')
      },
      exit: function(direction) {
        $(this.element).textillate('out')
      }
    });
  });
});

答案 1 :(得分:0)

这对我有用。需要将所有内容包装在.each()函数中。将lettering替换为您的班级名称,您应该好好去。

  $('.lettering').each(function() {
    var animatelettering = $('.lettering').each(function(){
        $(this).textillate({ 
            autoStart: false,
            in: { effect: 'flipInY' },
            out: { effect: 'fadeOut', sync: true, }
        });
    });
    new Waypoint.Inview({
      element: this,
      enter: function(direction) {
      },
      entered: function(direction) {
        animatelettering.textillate('in')
      },
      exit: function(direction) {
        animatelettering.textillate('out')
      },
      exited: function(direction) {
      }
    });
  });