javascript 如何在mouseDown按下js时实现mousemove

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30817534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:44:05  来源:igfitidea点击:

how to implement mousemove while mouseDown pressed js

javascriptjquerymouseeventmousemovemousedown

提问by M1M6

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.

仅当鼠标按下并移动时,我才需要执行“OK Moved”。

I used this code

我用了这个代码

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

回答by Tobías

Use the mosemoveevent.

使用mosemove事件。

From mousemoveand mouseoverjquery docs:

来自mousemovemouseoverjquery 文档:

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

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

mousemove当鼠标指针在元件内移动事件被发送给一个元素。

mouseover当鼠标指针进入元素事件被发送给一个元素。

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/

https://jsfiddle.net/n4820hsh/

回答by Algy Taylor

In pure javascript, you can achieve this with

在纯 javascript 中,您可以使用

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

(注意:在上面的示例中,您不需要该函数 - 您可以将其称为mouseMoveWhilstDown(document.getElementById('move'), console.log),但除了将其输出到控制台之外,您可能还想用它做一些事情!)