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

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

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

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

是否可以检测scroll事件是由用户还是由jQuery animatefunction触发的?

我正在尝试阻止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); }); 

这段代码似乎合适:

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

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

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

也许: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'); } }); 

演示

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

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

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

更新:警告!

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

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

使用@Tony接受的答案和@DanielTonon的评论我提出了以下解决方案:

  var animatedScroll = false; var lastAnimatedScroll = false; $(window).scroll(function(event){ lastAnimatedScroll = animatedScroll; animatedScroll = $('html, body').is(':animated'); }); 

这似乎解决了提到的问题,即jquery删除.is(':animated')然后再滚动一个像素,这导致.is(':animated')以false结尾。 通过存储.is(':animated')倒数第二个版本,您可以(更确定)滚动是否为动画。

当你想知道滚动是否动画时,只需检查lastAnimatedScroll变量。

这还没有经过我的彻底测试,但在许多页面刷新时都是正确的,所以我认为它运行良好。

我建议首先创建一个javascript函数

 // Attaching scroll event when document/window is loaded function OnFirstLoad() { if (document.attachEvent) { document.attachEvent('onscroll', scrollEvent); } else if (document.addEventListener) { document.addEventListener('scroll', scrollEvent, false); } } 

然后,使用其中之一

  window.onload = OnFirstLoad; 

要么

  $(document).ready(function () { OnFirstLoad(); }); 

在此滚动事件是一个function

 function scrollEvent(e) { var body = document.body, html = document.documentElement; var docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); var currentScroll = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop; // implement your logic according to requirement }