我正在尝试检测鼠标移动的距离(以像素为单位)。我目前正在使用:
$(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);
});
但是,我觉得这不是正确的做法,或者是这样吗?它与我不一致。
以下是它现在如何运作的演示:http://jsfiddle.net/Em4Xu/1/
我实际上是在开发一种拖拉机drop plugin我想创建一个名为distance
的功能,就像draggable一样,你需要在拖动它之前拉动鼠标一定数量的像素。我不是100%确定如何做到这一点,所以首先我需要获取鼠标从startingTop和startingLeft位置移动的像素。
有人有任何建议吗?
答案 0 :(得分: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;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>
答案 1 :(得分: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);
});
答案 2 :(得分:6)
想出了与塞尔吉奥类似的东西,但是这将从鼠标按下的点开始计算出的不足,就像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;
});