how to implement mousemove while mouseDown pressed js

后端 未结 2 994
日久生厌
日久生厌 2021-02-14 09:23

I have to implement mouse move event only when mouse down is pressed.

I need to execute \"OK Moved\" only when mouse down and mouse move.

I used this code

<
2条回答
  •  孤独总比滥情好
    2021-02-14 09:53

    In pure javascript, you can achieve this with

    function mouseMoveWhilstDown(target, whileMove) {
        var endMove = function () {
            window.removeEventListener('mousemove', whileMove);
            window.removeEventListener('mouseup', endMove);
        };
    
        target.addEventListener('mousedown', function (event) {
            event.stopPropagation(); // remove if you do want it to propagate ..
            window.addEventListener('mousemove', whileMove);
            window.addEventListener('mouseup', endMove);   
        });
    }
    

    Then using the function along the lines of

    mouseMoveWhilstDown(
        document.getElementById('move'),
        function (event) { console.log(event); }
    );
    

    (nb: in the above example, you don't need the function - you could call it as mouseMoveWhilstDown(document.getElementById('move'), console.log), but you might want to do something with it other than output it to the console!)

提交回复
热议问题