如何区分手动滚动(通过鼠标滚轮/滚动条)和 Javascript/jQuery 滚动? [英] How can I differentiate a manual scroll (via mousewheel/scrollbar) from a Javascript/jQuery scroll?

查看:92
本文介绍了如何区分手动滚动(通过鼠标滚轮/滚动条)和 Javascript/jQuery 滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个 jsbin 示例,演示了该问题.

Here is a jsbin example demonstrating the problem.

更新 2:
这是 固定版本 感谢 fudgey.

基本上,我有以下 javascript 将窗口滚动到页面上的锚点:

Basically, I have the following javascript which scrolls the window to an anchor on the page:

 // get anchors with href's that start with "#"
 $("a[href^=#]").live("click", function(){
     var target = $($(this).attr("href"));
     // if the target exists: scroll to it...
     if(target[0]){
         // If the page isn't long enough to scroll to the target's position
         // we want to scroll as much as we can. This part prevents a sudden 
         // stop when window.scrollTop reaches its maximum.
         var y = Math.min(target.offset().top, $(document).height() - $(window).height());
         // also, don't try to scroll to a negative value...
         y=Math.max(y,0);
         // OK, you can scroll now...
         $("html,body").stop().animate({ "scrollTop": y }, 1000);
     }
     return false;
 });

它工作得很好......直到我手动尝试滚动窗口.当滚动条或鼠标滚轮滚动时,我需要停止当前的滚动动画……但我不知道该怎么做.

It works perfectly......until I manually try to scroll the window. When the scrollbar or mousewheel is scrolled I need to stop the current scroll animation...but I'm not sure how to do this.

这可能是我的起点...

This is probably my starting point...

$(window).scroll(e){
    if(IsManuallyScrolled(e)){
        $("html,body").stop();
    }
} 

...但我不确定如何编写 IsManuallyScrolled 函数.我已经在 Google Chrome 的控制台和 AFAIK 中检查了 e(event 对象),没有办法区分手动滚动和 jQuery 的 animate() 滚动.

...but I'm not sure how to code the IsManuallyScrolled function. I've checked out e (the event object) in Google Chrome's console and AFAIK there is not way to differentiate between a manual scroll and jQuery's animate() scroll.

如何区分手动滚动和通过 jQuery 的 $.fn.animate 函数调用的滚动?

How can I differentiate between a manual scroll and one called via jQuery's $.fn.animate function?

推荐答案

试试这个功能:

$('body,html').bind('scroll mousedown wheel DOMMouseScroll mousewheel keyup', function(e){
 if ( e.which > 0 || e.type == "mousedown" || e.type == "mousewheel"){
  $("html,body").stop();
 }
})

此外,您是否看过本教程?

更新:现代浏览器现在使用 "wheel" 作为事件,所以我已经将它包含在上面的代码中.

Update: Modern browsers now use "wheel" as the event, so I've included it in the code above.

这篇关于如何区分手动滚动(通过鼠标滚轮/滚动条)和 Javascript/jQuery 滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆