jquery mousewheel:检测车轮何时停止?

Mou*_*ard 20 jquery event-handling mousewheel

我正在使用Jquery 鼠标滚轮插件,我希望能够检测用户何时完成使用滚轮.与可拖动内容中的stop:event类似的功能.有人能指出我正确的方向吗?

Nic*_*ver 37

这里没有"停止"事件 - 当你滚动时你得到一个事件,所以每次鼠标轮事件发生时事件都会被触发......当没有什么事情你就不会得到任何事件而你的处理程序也不会被触发.

然而,您可以检测用户何时没有使用它,例如250ms,如下所示:

$("#myElem").mousewheel(function() {
  clearTimeout($.data(this, 'timer'));
  $.data(this, 'timer', setTimeout(function() {
     alert("Haven't scrolled in 250ms!");
     //do something
  }, 250));
});
Run Code Online (Sandbox Code Playgroud)

你可以在这里尝试一下,我们所做的只是在每次使用中存储超时$.data(),如果你在那个时间用完之前再次使用它,它会被清除......如果没有,那么你想要运行的任何代码都会被激活,用户已经使用鼠标滚轮"完成"了你正在测试的任何时间段.

  • 不适用于像 Apple 笔记本电脑或 Magic 鼠标那样的动态滚动。 (2认同)

abe*_*ier 9

完成Nick Craver的回答:

var wheeldelta = {
  x: 0,
  y: 0
};
var wheeling;
$('#foo').on('mousewheel', function (e) {
  if (!wheeling) {
    console.log('start wheeling!');
  }

  clearTimeout(wheeling);
  wheeling = setTimeout(function() {
    console.log('stop wheeling!');
    wheeling = undefined;

    // reset wheeldelta
    wheeldelta.x = 0;
    wheeldelta.y = 0;
  }, 250);

  wheeldelta.x += e.deltaFactor * e.deltaX;
  wheeldelta.y += e.deltaFactor * e.deltaY;
  console.log(wheeldelta);
});
Run Code Online (Sandbox Code Playgroud)

滚动输出:

start wheeling!
Object {x: -1, y: 0}
Object {x: -36, y: 12}
Object {x: -45, y: 12}
Object {x: -63, y: 12}
Object {x: -72, y: 12}
Object {x: -80, y: 12}
Object {x: -89, y: 12}
Object {x: -97, y: 12}
Object {x: -104, y: 12}
Object {x: -111, y: 12}
Object {x: -117, y: 12}
Object {x: -122, y: 12}
Object {x: -127, y: 12}
Object {x: -131, y: 12}
Object {x: -135, y: 12}
Object {x: -139, y: 12}
Object {x: -145, y: 12}
Object {x: -148, y: 12}
Object {x: -152, y: 12}
Object {x: -154, y: 12}
Object {x: -156, y: 12}
Object {x: -157, y: 12}
Object {x: -158, y: 12}
Object {x: -159, y: 12}
Object {x: -161, y: 12}
Object {x: -162, y: 12}
Object {x: -164, y: 12}
Object {x: -166, y: 12}
Object {x: -167, y: 12}
Object {x: -169, y: 12}
stop wheeling!
Run Code Online (Sandbox Code Playgroud)