how to implement mousemove while mouseDown pressed js

时光怂恿深爱的人放手 提交于 2019-12-04 21:32:25

问题


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

 $(".floor").mousedown(function() {
  $(".floor").bind('mouseover',function(){
      alert("OK Moved!");
  });
})
.mouseup(function() {
 $(".floor").unbind('mouseover');
});

回答1:


Use the mosemove event.

From mousemove and mouseover jquery docs:

The mousemove event is sent to an element when the mouse pointer moves inside the element.

The mouseover event is sent to an element when the mouse pointer enters the element.

Example: (check console output)

$(".floor").mousedown(function () {
    $(this).mousemove(function () {
        console.log("OK Moved!");
    });
}).mouseup(function () {
    $(this).unbind('mousemove');
}).mouseout(function () {
    $(this).unbind('mousemove');
});

https://jsfiddle.net/n4820hsh/




回答2:


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!)



来源:https://stackoverflow.com/questions/30817534/how-to-implement-mousemove-while-mousedown-pressed-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!