如何检测用户鼠标移动的距离?

Sha*_*313 12 javascript math jquery

我正在尝试检测鼠标移动的距离(以像素为单位).我目前正在使用:

$(document).mousemove(function(event) {
    var startingTop = 10,
        startingLeft = 22,
        math = Math.abs(((startingTop - event.clientY) + (startingLeft - event.clientX)) + 14) + 'px';
    $('span').text('From your starting point(22x10) you moved:   ' + math);
});
Run Code Online (Sandbox Code Playgroud)

但是,我觉得这不是正确的方法,或者是这样吗?它与我不一致.

以下是它现在如何工作的演示:http://jsfiddle.net/Em4Xu/1/

额外细节:

我实际上正在开发一个拖放插件,我想创建一个名为的distance函数,就像draggable一样,你需要在拖动它之前拉动鼠标一定数量的像素.我不是100%确定如何做到这一点,所以首先我需要获取鼠标从startingTop和startingLeft位置移动的像素.

有没有人有什么建议?

Ser*_*sev 11

这是一个测量鼠标移动距离的版本:

var totalDistance = 0;
var lastSeenAt = {x: null, y: null};

$(document).mousemove(function(event) {
    if(lastSeenAt.x) {
        totalDistance += Math.sqrt(Math.pow(lastSeenAt.y - event.clientY, 2) + Math.pow(lastSeenAt.x - event.clientX, 2));
        
    $('span').text('So far your mouse ran this many pixels:   ' + Math.round(totalDistance));
    
    }
    lastSeenAt.x = event.clientX;
    lastSeenAt.y = event.clientY;
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>
Run Code Online (Sandbox Code Playgroud)


Ser*_*sev 8

你的数学错了.这是改进版本:http://jsfiddle.net/stulentsev/Em4Xu/26/

$(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);
});
Run Code Online (Sandbox Code Playgroud)


Mot*_*tes 7

想出了与塞尔吉奥类似的东西,但是这将从鼠标被按下的位置计算出的不足,并且像jfriend所说的两点之间的距离,

d =((x1-x2)^ 2 +(y1-y2)^ 2)^(1/2)

var totalMovement = 0;
var lastX = -1;
var lastY = -1;
var startX = -1;
var startY = -1;

$(document).mousemove(function(event) {

    if (startX == -1) {
        return;
    }
    if (startY == -1) {
        return;   
    }

    totalMovement += Math.sqrt(Math.pow(lastY - event.clientY, 2) + Math.pow(lastX - event.clientX, 2));

    $('span').text('From your starting point (' + startX + 'x' + startY + ') you moved:   ' + totalMovement);

    lastX = event.clientX;
    lastY = event.clientY;

});


$(document).mousedown(function(event) {

 startX = event.clientX;
 startY = event.clientY;
 lastX = event.clientX;
 lastY = event.clientY;

});


$(document).mouseup(function(event) {

 startX = -1;
 startY = -1;
 totalMovement = 0;
 lastX = 0;
 lastY = 0;

});
Run Code Online (Sandbox Code Playgroud)