Javascript 计算按下鼠标按钮时鼠标移动的距离
我尝试在按下鼠标按钮时,按鼠标移动的距离移动画布中的元素Javascript 计算按下鼠标按钮时鼠标移动的距离,javascript,Javascript,我尝试在按下鼠标按钮时,按鼠标移动的距离移动画布中的元素 $("#hdr").on("mousemove", function(e) { console.log(e); if (e.which == 1) { console.log(e.pageX + " / " + e.pageY + "//" + e.offsetY +" / "+ e.offsetX); } }); 获取最近的鼠标位置没有问题,但我不
$("#hdr").on("mousemove", function(e) {
console.log(e);
if (e.which == 1) {
console.log(e.pageX + " / " + e.pageY + "//" + e.offsetY +" / "+ e.offsetX);
}
});
获取最近的鼠标位置没有问题,但我不知道如何存储初始鼠标位置,以计算移动距离。您可以使用所需的值设置变量。按下鼠标按钮时,存储此位置的值,并将其用作mousemove事件中的参考,以计算距离。如果只想在按住鼠标按钮时计算距离,还可以存储鼠标按钮当前是向下还是向上 jsfiddle: 编辑:通过组合事件(mousedown和mouseup)并反转每个事件上的布尔值来编写它的更简洁的方法
$('#hdr').on('mousedown mouseup', function (e) {
mouseReference.buttonDown = !mouseReference.buttonDown
mouseReference.x = e.pageX
mouseReference.y = e.pageY
}).on('mousemove', function (e) {
if (e.which === 1 && mouseReference.buttonDown) {
// The location (x, y) the mouse was originally pressed
console.log('refernce x: ', mouseReference.x)
console.log('refernce y: ', mouseReference.y)
// The new location of the mouse while being moved
console.log('new x: ', e.pageX)
console.log('new y: ', e.pageY)
// Calculate distance here using the e.pageX / e.pageY and reference location
}
})
可以使用所需的值设置变量。按下鼠标按钮时,存储此位置的值,并将其用作mousemove事件中的参考,以计算距离。如果只想在按住鼠标按钮时计算距离,还可以存储鼠标按钮当前是向下还是向上 jsfiddle: 编辑:通过组合事件(mousedown和mouseup)并反转每个事件上的布尔值来编写它的更简洁的方法
$('#hdr').on('mousedown mouseup', function (e) {
mouseReference.buttonDown = !mouseReference.buttonDown
mouseReference.x = e.pageX
mouseReference.y = e.pageY
}).on('mousemove', function (e) {
if (e.which === 1 && mouseReference.buttonDown) {
// The location (x, y) the mouse was originally pressed
console.log('refernce x: ', mouseReference.x)
console.log('refernce y: ', mouseReference.y)
// The new location of the mouse while being moved
console.log('new x: ', e.pageX)
console.log('new y: ', e.pageY)
// Calculate distance here using the e.pageX / e.pageY and reference location
}
})
您是否尝试过使用
mousedown
事件来记住坐标?您是否尝试过使用mousedown
事件来记住坐标?正如@Art3mix提到的,globals不是一个好的做法,但是如果您愿意,您可以将其放在闭包中,或者放在代码中已经存在的对象的内部。有了更多的上下文,我可以帮助您更清晰一些,但我不确定您的代码库的其余部分是什么样子的。希望这有帮助!:)正如@Art3mix所提到的,globals不是一个好的实践,但是如果您愿意,可以将它放在闭包中,或者放在代码中已经存在的对象中。有了更多的上下文,我可以帮助您更清晰一些,但我不确定您的代码库的其余部分是什么样子的。希望这有帮助!:)