How can I retrieve all mouse coordinates between mousedown to mouseup event

后端 未结 3 1080
星月不相逢
星月不相逢 2020-12-12 02:12

As per the jQuery docs below code can be used to capture mouseup and mouse down events. But my requirement is bit different

$(\"#dic\").mouseup(function ()          


        
相关标签:
3条回答
  • 2020-12-12 02:43
    var X = [],
        Y = [],
        i = -1;
    $("#dic").mouseup(function(e) {
        ++i;
        X[i] = e.pageX;
        Y[i] = e.pageY;
        // reset everything on mouseup
        X = [];
        Y = [];
        i = -1;
    }).mousedown(function(e) {
        ++i;
        X[i] = e.pageX;
        Y[i] = e.pageY;
        console.log(X);
    }).mousemove(function(e) {
        ++i;
        X[i] = e.pageX;
        Y[i] = e.pageY;
    });
    

    DEMO

    0 讨论(0)
  • 2020-12-12 02:46
    var x = [], y = [], i = 0;
    
    $("#dic").mouseup(function (e) {
        $('#status').html(e.pageX +', '+ e.pageY + ' up');
        x[i] = e.pageX;
        y[i++] = e.pageY;
    
        console.log(x);
        console.log(y);
    });
    
    $("#dic").mousedown(function (e) {
        $('#status').html(e.pageX +', '+ e.pageY + ' down');
        i = 0;
        x[i] = e.pageX;
        y[i++] = e.pageY;
    });
    
    $("#dic").mousemove(function (e) {
        $('#status').html(e.pageX +', '+ e.pageY + ' move');
        x[i] = e.pageX;
        y[i++] = e.pageY;
    });
    

    This will begin recording mouse positions on mousedown and you can see the output on the console on mouseup. Then you can calculate the distance as thecodeparadox described with the first and last items of the arrays, or any other points in between the start and end.

    Code on JSFiddle

    0 讨论(0)
  • 2020-12-12 02:49

    If you need to captue all points the mouse moves through during a drag, bind/unbind a new mousemove handler:

    var allPoints = [];
    $("#dic").mouseup(function (e) {
        $(this).unbind("mousemove", trackPoints);
    }).mousedown(function (e) {
        $(this).bind("mousemove", trackPoints); 
    });
    
    function trackPoints(e) {
        allPoints.push({ x: e.pageX, y: e.pageY });
    }
    

    This way, trackPoints will start firing when the mouse is down and stop when it goes back up.

    You may also want to add a if(e.which == 1) to the top of your mouseup and mousedown handlers so that they perform the bind for a left mouse button only, not middle or right buttons.

    0 讨论(0)
提交回复
热议问题