jQuery Mousemove:触发更改5px

时间:2012-10-09 01:09:03

标签: events triggers jquery mousemove

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

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

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

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

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

非常感谢,

安东尼奥

1 个答案:

答案 0 :(得分:3)

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

This post非常相关。

以下是基本代码:

$(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在谈论什么。我使用上面的代码来提出this fiddle。它会跟踪您屏幕左上角的当前位置,并检查您的差异是否为> 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);
    }
});​