区分用户滚动和使用Javascript以编程方式滚动

Leo*_*ang 31 javascript jquery

我正在使用JQuery创建滚动效果,我想知道是否可以区分用户滚动和编程滚动.

我有这样的事情:

$('#element').on('scroll',function(e){
    $('#element').stop(true); // stop previous scrolling animation
    $('#element').animate({ // start new scrolling animation (maybe different speed, different direction, etc)
        scrollTop:...
    });
});
Run Code Online (Sandbox Code Playgroud)

但是,在动画的每个步骤中都会触发此事件.如何判断此事件是由用户还是动画触发?

dev*_*bmw 6

使用变量确定何时以编程方式滚动

例:

var programScrolling = false;

$('#element').on('scroll',function(e){
    if (programScrolling) {
        return;
    }

    $('#element').stop(true); // stop scrolling animation

    programScrolling = true;

    $('#element').animate({
        scrollTop:...
    });

    programScrolling = false;
});
Run Code Online (Sandbox Code Playgroud)

不确定这是不是你想要的,但这个概念应该有效.

  • 这个答案是不正确的。$('#element')。animate(...)将启动动画,但它会在动画完成之前返回*,因为动画是异步过程。它不会阻止。因此,“ programScrolling = false;”将在动画结束之前执行。 (3认同)

Ara*_*Rey 5

我将为不同类型的滚动创建函数以检测它们,并为所有滚动调用一个滚动处理程序,如下所示:

JS小提琴

$(window).bind('mousewheel DOMMouseScroll', function(event){
    var direction;
    if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
        direction = 'up';
    }
    else {
        direction = 'down';
    }
    scrollHandler(direction, 'mouseWheel');
    event.preventDefault();
});

var scrollHandler = function(direction, origin) {
    var height = $(document).scrollTop();
    var movement = (direction == 'up') ? -100 : 100;
    console.log(origin);
    $('body').stop(true);
    $('body').animate({
        scrollTop: height + movement
    }, 250);
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以根据事件的来源来做不同的事情!
您还可以检查用户是否向与屏幕滚动相同的方向滚动并执行其他操作,或者通过mousewheel事件传递的信息执行任何所需的操作。

原装鼠标滚轮事件函数从复制答案