检测是否在jQuery中手动触发滚动事件

Blu*_*ADe 12 javascript jquery events scroll jquery-events

这个问题很久以前就已在这里提出过:

检测用户的jquery事件触发器或代码调用

但它从来没有得到最终的回答(或者我可能根本无法正确搜索).

是否可以检测scroll用户或jQuery animate函数是否触发了事件?

我正在尝试阻止scroll事件触发自己,同时做这样的事情:

$(document).scroll(function(){
    $("html").stop(true);
    var number = 400; //some other stuff is happening here
    clearTimeout(tout);
    tout = setTimeout(function(){
        if(top == $(document).scrollTop()){
            $("html").animate({
                scrollTop: (number),
                easing: "easeInQuad",
                duration: 110
            });
        }
    },120);
});
Run Code Online (Sandbox Code Playgroud)

这段代码似乎很合适:

$('#scroller').scroll(function(e) {
    if (e.originalEvent) {
        console.log('scroll happen manual scroll');
    } else {
        console.log('scroll happen by call');
    }
});
Run Code Online (Sandbox Code Playgroud)

但是该originalEvent对象无法正确检测动画触发器.

有没有其他方法可以做到这一点?

Ton*_*ony 19

也许:animated选择器会帮助你:

$('#scroller').scroll(function(e) {
    if ($(this).is(':animated')) {
        console.log('scroll happen by animate');
    } else if (e.originalEvent) {
        // scroll happen manual scroll
        console.log('scroll happen manual scroll');
    } else {
        // scroll happen by call
        console.log('scroll happen by call');
    }
});
Run Code Online (Sandbox Code Playgroud)

演示

  • 这不能按预期工作,因为jquery将`.is(':animated')`更改为false,然后再滚动1个像素.那1px的scroll会触发scroll事件,但这次使用`.is(':animated')`设置为false会使`.is(':animated')`对于这个用例几乎完全无用,除非你能找到一种方法围绕这个bug. (2认同)

Dan*_*non 6

我不知道这对触摸屏设备的效果如何,但至少在桌面上这对我有用

$(window).on('mousewheel', function(){
    //code that will only fire on manual scroll input
});

$(window).scroll(function(){
    //code that will fire on both mouse scroll and code based scroll
});
Run Code Online (Sandbox Code Playgroud)

我不认为有一种方法只能定位动画卷轴(接受的答案对我不起作用).

更新:警告!

不幸的是,'mousewheel'似乎没有拿起手动抓住滚动条并拖动它的用户或使用滚动条箭头按钮的用户:(

这仍适用于触摸屏设备,因为它们的滑动似乎算作鼠标滚动.但这对桌面用户来说不是一个很好的解决方案.