区分用户滚动和使用Javascript编程滚动

Distinguishing between the user scrolling and programmatically scrolling using Javascript

本文关键字:滚动 Javascript 编程 用户      更新时间:2023-09-26

我正在使用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:...
    });
});

然而,这个事件在动画的每一步都被触发。我怎么知道这个事件是由用户触发的还是由动画触发的?

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

的例子:

var programScrolling = false;
$('#element').on('scroll',function(e){
    if (programScrolling) {
        return;
    }
    $('#element').stop(true); // stop scrolling animation
    programScrolling = true;
    $('#element').animate({
        scrollTop:...
    });
    programScrolling = false;
});

不确定这是不是你想要的,但是这个概念应该是可行的。

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

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);
};

然后你可以根据事件的起源做不同的事情!
你也可以检查用户滚动到与屏幕滚动相同的方向,并做一些不同的事情,或者你想用mousewheel事件传递的信息。

复制自THIS answer的鼠标滚轮事件函数

我建议可能使用. originalevent方法。缺点是,这非常依赖于浏览器。在这里看到的。希望以下内容对您有所帮助:

$('#element').scroll(function(e){
    var humanScroll = e.originalEvent === undefined;
    if(humanScroll) {
        $(this).stop(true);
    }
})