jQuery Mousemove:触发改变5px [英] jQuery Mousemove: trigger on change of 5px

查看:223
本文介绍了jQuery Mousemove:触发改变5px的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

到目前为止,它的效果很好,我只是想要每5像素移动一次地启动mousemove事件,而不是逐个像素。我试过编写一个简单的代码:

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

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

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.

您是否知道如何每5个像素触发一次?

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

非常感谢,

安东尼奥

推荐答案

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

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.

这篇文章是非常相关的。

这是基本代码:

$(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像素。

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.

新脚本:

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

这篇关于jQuery Mousemove:触发改变5px的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆