动画未完成时,jQuery鼠标滚轮仅触发一次

时间:2014-10-30 02:24:24

标签: jquery jquery-animate bind mousewheel unbind

我有两个函数animation1()animation2()。这些函数中的每一个都在链中包含一些动画(animate())。每个动画集都有两部分:

  1. 在scene1中移动对象>隐藏它们>在场景2上显示对象。

  2. 第二个动画集是反向的 - 在scene2上隐藏对象>在scene1上显示对象并将它们移到右侧

  3. 动画正在运作。

    我需要的是使用以下规则将这些动画绑定到mousewheel

    • 当我向下滚动>运行animation1
    • 当我向上滚动>运行animation2
    • 在animation1尚未完成时不运行animation2(反之亦然)
    • (TODO)因鼠标轮而多次运行naimation1(动画2相同)

    这是我的代码,它正在运行但多次运行并因为mousewheel deltas多次触发而造成大混乱。我尝试了很多解决方案,没有任何运气。我也试过解除绑定mousewheel,这是有效的;但我不知道如何重新绑定它并向上滚动。

    $(window).bind('DOMMouseScroll MozMousePixelScroll mousewheel onmousewheel', function(e){
        //$(this).unbind('DOMMouseScroll MozMousePixelScroll mousewheel onmousewheel');
        if (e.originalEvent.wheelDelta < 0 || e.originalEvent.detail > 0) {
          if ($('.scene1 .image').is(':visible') && $('#content').find(":animated").length === 0) {
            animation1();
          }
        }
        else {
          if ($('.scene2 .image').is(':visible') && $('#content').find(":animated").length === 0) {
            animation2();
          }
        }
    });
    

    感谢您的任何建议!

    更新 这时,这是我最好的解决方案..动画只被触发一次(使用jquery.mousewheel,但也可以在没有这个lib的情况下使用) http://jsfiddle.net/wkupb1Ln/6/

    $('#content').mousewheel(function(event) {
        if ($('.image').is(':animated') ) {
            return false;
        }
        if ( (event.deltaY < 0) && $('.scene2 .image').hasClass('invisible') ) {
            animation1();
        }
        if ( (event.deltaY > 0) && $('.scene1 .image').hasClass('invisible') ) {
            animation2();
        }
    });
    

1 个答案:

答案 0 :(得分:1)

尝试使用此处的scrollstop / scrollstart插件:https://github.com/ssorallen/jquery-scrollstop

然后我会将代码重构为类似下面的内容,你可以通过计算一定时间间隔后的滚动来测量“delta”(这里是250ms)

$(window).on("scrollstart", function() {
  var Position1 = $window.scrollTop();
  setTimeout(function () {
    var Position2 = $window.scrollTop(), delta = Position2 - Position1;
    if (delta < 0 && $('.scene1 .image').is(':visible') && $('#content').find(":animated").length === 0) {
      animation1();
    } else {
      if (delta > 0 && $('.scene2 .image').is(':visible') && $('#content').find(":animated").length === 0) {
        animation2();
      }
    }
  }, 250);
});

绑定到“scrollstart”应确保相应的功能仅触发一次。