jQuery Mousemove:触发更改5px

出于多种技术原因,我在jQuery上实现了自己的’draggable’function,而不是使用jQuery UI,我正在使用mousedown和mousemove事件来监听用户试图拖动元素。

它到目前为止工作得很好,我只想每隔5像素运动启动一次mousemove事件,而不是像素一样。 我试过编码很简单:

$('#element').bind('mousemove', function(e) { if(e.pageX % 5 == 0) { // Do something } }); 

但是,每5个像素的移动不稳定,有时如果移动鼠标太快,它将跳过几个步骤。 我认为这是因为当快速移动鼠标时,jQuery不会触发每个像素的事件。

你们知道如何每5个像素触发一次事件吗?

非常感谢,

安东尼奥

您的代码没有考虑拖动的开始位置。 e.pageX只会给你页面坐标,而不是差异。 您需要检查移动距离的变化。

这篇文章非常相关。

这是基本代码:

 $(document).mousemove(function(event) { var startingTop = 10, startingLeft = 22, math = Math.round(Math.sqrt(Math.pow(startingTop - event.clientY, 2) + Math.pow(startingLeft - event.clientX, 2))) + 'px'; $('span').text('From your starting point(22x10) you moved: ' + math); }); 

编辑:现在我想我明白OP在谈论什么。 我使用上面的代码来提出这个小提琴 。 它跟踪您屏幕左上角的当前位置,并检查您的差异是否大于5个像素。

新脚本:

 var oldMath = 0; $(document).mousemove(function(event) { var startingTop = 10, startingLeft = 22, math = Math.round(Math.sqrt(Math.pow(startingTop - event.clientY, 2) +Math.pow(startingLeft - event.clientX, 2))) + 'px'; $('#currentPos').text('you are at :' + math); if(Math.abs(parseInt(math) - oldMath) > 5){ //you have moved 5 pixles, put your stuff in here $('#logPos').append('5'); //keep track of your position to compare against next time oldMath = parseInt(math); } });​