计算在按下鼠标按钮期间鼠标移动的距离

时间:2018-12-01 17:51:30

标签: javascript

我尝试通过按鼠标按钮的同时移动鼠标的距离来移动画布中的元素。

    $("#hdr").on("mousemove", function(e) {
        console.log(e);
        if (e.which == 1) {
            console.log(e.pageX + " / " + e.pageY + "//" + e.offsetY +" / "+ e.offsetX);
        }
    });

获取最近的鼠标位置没问题,但是我不知道如何存储鼠标的初始位置来计算移动距离。

1 个答案:

答案 0 :(得分:2)

您可以使用所需的值设置变量。按下鼠标按钮时,请存储该位置的值,并将其用作mousemove事件中的参考以计算距离。如果只想在按住时计算距离,还可以存储鼠标按钮当前是向下还是向上。

jsfiddle:https://jsfiddle.net/xpvt214o/976224/

const mouseReference = {
    buttonDown: false,
    x: false,
    y: false
}

$('#hdr').on('mousedown', function (e) {
    mouseReference.buttonDown = true
    mouseReference.x = e.pageX
    mouseReference.y = e.pageY
}).on('mouseup', function (e) {
     mouseReference.buttonDown = false
}).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和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
    }
})