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

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

然后你可以根据事件的起源做不同的事情!
您还可以检查用户是否滚动到与屏幕滚动相同的方向,并使用鼠标滚轮事件传递的信息执行不同的操作或任何您想要的操作。

从这个答案复制的原始鼠标滚轮事件function

我建议可能使用.originalEvent方法。 缺点是,这取决于浏览器。 看到这里 。 希望以下有助于:

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