Events jQuery Mousemove:更改5px时触发

Events jQuery Mousemove:更改5px时触发,events,triggers,jquery,mousemove,Events,Triggers,Jquery,Mousemove,出于许多技术原因,我在jQuery上实现了我自己的“可拖动”功能,而不是使用jQuery UI,并且我使用mousedown和mousemove事件来监听试图拖动元素的用户 到目前为止,它工作得很好,我只想每5像素的移动触发mousemove事件,而不是逐像素触发。我尝试过编写一个简单的: $('#element').bind('mousemove', function(e) { if(e.pageX % 5 == 0) { // Do something } }

出于许多技术原因,我在jQuery上实现了我自己的“可拖动”功能,而不是使用jQuery UI,并且我使用mousedown和mousemove事件来监听试图拖动元素的用户

到目前为止,它工作得很好,我只想每5像素的移动触发mousemove事件,而不是逐像素触发。我尝试过编写一个简单的:

$('#element').bind('mousemove', function(e) {
    if(e.pageX % 5 == 0) {
        // Do something
    }
});
但是,每5个像素的移动并不稳定,有时如果移动鼠标太快,它会跳过几个步骤。我认为这是因为当鼠标移动得非常快时,jQuery不会触发每个像素的事件

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

非常感谢


Antonio

您的代码不考虑拖动的起始位置
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);
    }
});​

谢谢你的回答,davehale23,但它没有回答我的问题。我提供的代码是描述我的问题的基本片段,即如何每X像素触发mousemove。我添加了一个编辑,这更像你所说的吗?