jQuery Mousemove: trigger on change of 5px

怎甘沉沦 提交于 2019-12-12 10:09:32

问题


For a number of technical reasons, I'm implementing my own 'draggable' feature on jQuery, rather than using jQuery UI, and I'm using mousedown and mousemove events to listen for the user trying to drag an element.

It works good so far, I would just like to fire up the mousemove event every 5 px of movement, rather than pixel by pixel. I've tried coding a simple:

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

However, the movement is not stable every 5 pixels, and sometimes if you move the mouse too fast, it will skip several steps. I think this is because when moving the mouse very fast, jQuery will not trigger the event every pixel.

Do you guys know how to trigger the event every 5 pixels?

Thanks a lot,

Antonio


回答1:


Your code does not take into account where your drag started. e.pageX will just give you page coordinates, not differences. You need to check for the change in distance moved.

This post is pretty relevant.

Here is the basic code:

$(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);
});

EDIT: Now I think I understand what the OP is talking about. I used the above code to come up with this fiddle. It tracks your current position in relation to the Top Left of the screen and it checks to see if your difference is > 5 pixles.

New script:

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);
    }
});​


来源:https://stackoverflow.com/questions/12791549/jquery-mousemove-trigger-on-change-of-5px

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!