我没有从stackoverflow获得精确的解决方案/计算,所以我创建了一个问题
var timestamp = null;
var mY = 0;
$(document).mousemove(function(e) {
var now = Date.now();
currentmY = e.pageY;
mY = e.pageY;
timestamp = now;
});
当鼠标移动垂直角度时,我需要获得速度值。
答案 0 :(得分:2)
速度只是距离除以花费的时间:
speed = distance / time
距离为currentmY - mY
,时间为now - timestamp
。所以最后,你得到:
var timestamp = 0;
var mY = 0;
$(document).mousemove(function(e) {
var now = Date.now();
currentmY = e.screenY;
var dt = now - timestamp;
var distance = Math.abs(currentmY - mY);
var speed = Math.round(distance / dt * 1000);
console.log(dt, distance, speed);
document.getElementById("speed").innerHTML = speed;
mY = currentmY;
timestamp = now;
});
请注意* 1000
,因为时间戳以毫秒为单位。速度在像素/秒。
答案 1 :(得分:1)
以下代码将持续更新鼠标在跨度中的垂直移动速度,其中id ="更新速度"。代码是自我解释且易于理解,它只保存当前位置,先前位置,当前时间和之前的时间,然后使用此公式计算速度(速度=(pos2 - pos1)/(time2 - time1)。
<强> HTML 强>
<span id="update-speed">Update speed</span>
JS
var prev_time = new Date();
var prev_pos_y = 0;
$(document).mousemove(function(e) {
var now = new Date();
current_pos_y = e.pageY;
time_interval = now.getTime() - prev_time.getTime();
if(time_interval != 0)
{
speed = ( Math.abs(current_pos_y - prev_pos_y) / time_interval );
}
else
speed = 0;
console.log(speed);
$('#update-speed').text(speed);
prev_time = now;
prev_pos_y = current_pos_y;
});