我试图计算鼠标的瞬时速度。
为此,我创建x1 = e.pageX
来存储起始坐标,并t1 = new Date()...
来获取开始时间。然后,当鼠标停止移动时,我想在100米/秒后进行回调,并计算新的pageX
和t2
...这是我可以获得给定时间间隔的斜率。 .. x2 - x1/t2 - t1
问题:当我调用回调时,我尝试使用bind
将事件e
(mousemove(function(e)
)的上下文绑定到回调。我做错了吗?
var mY = 0,
mX = 0,
slope = 0,
vel = 0,
thread;
$(document).ready(function(){
$(".box").mousemove(function(e) {
getDirection(e);
var x1 = e.pageX,
t1 = new Date().getTime();
clearTimeout(thread);
thread = setTimeout(callback.bind(this), 100);
});
});
function callback(e) {
var x2 = e.pageX,
t2 = new Date().getTime(),
xDist = x2 - x1,
time = t2 - t1;
log(x2 + ", " + x1);
slope = xDist/time;
log("mouse has stopped");
}
答案 0 :(得分:1)
我做错了吗?
是的,你永远不会将e
传递给回调。看起来像你想要的
callback.bind(this, e)
在事件处理程序中,this
引用处理程序绑定的DOM元素,而不是事件。