Javascript 拖动时获取鼠标位置(JS + HTML5)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5798167/
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-08-23 18:55:05  来源:igfitidea点击:

Getting mouse position while dragging (JS + HTML5)

javascripthtml

提问by NRaf

I'm currently implementing a small demo app trying to get my head around drag and drop with HTML5. What I'm trying to do at the moment is getting the position of the cursor when the user is dragging however I'm having some issues.

我目前正在实施一个小型演示应用程序,试图用 HTML5 进行拖放操作。我现在要做的是在用户拖动时获取光标的位置,但是我遇到了一些问题。

It seems that the 'mousemove' event doesn't get fired when dragging which is stopping me from figuring out the current position of the mouse. I could use the 'drag' event, however I can't figure out how to get the position from the 'drag' event object.

拖动时似乎没有触发 'mousemove' 事件,这使我无法确定鼠标的当前位置。我可以使用 'drag' 事件,但是我不知道如何从 'drag' 事件对象中获取位置。

回答by mattsven

//  JavaScript

document.addEventListener("dragover", function(e){
    e = e || window.event;
    var dragX = e.pageX, dragY = e.pageY;

    console.log("X: "+dragX+" Y: "+dragY);
}, false);

//  jQuery

$("body").bind("dragover", function(e){
    var dragX = e.pageX, dragY = e.pageY;

    console.log("X: "+dragX+" Y: "+dragY);
});

Runnable code snippet below:

可运行的代码片段如下:

// JavaScript (a really great library that extends jQuery, check it out)

document.addEventListener("dragover", function(e){
e = e || window.event;
var dragX = e.pageX, dragY = e.pageY;

console.log("X: "+dragX+" Y: "+dragY);
}, false);

// jQuery (the native-language JavaScript is written in)

$("body").bind("dragover", function(e){
var dragX = e.pageX, dragY = e.pageY;

console.log("X: "+dragX+" Y: "+dragY);
});
<!doctype>
<html>
  <head><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></head>
  <body>LOL drag something over me (open the console)</body>
</html>

回答by alex

document.ondragover = function(evt) {
    evt = evt || window.event;
    var x = evt.pageX,
        y = evt.pageY;

    console.log(x, y);
}

jsFiddle.

js小提琴

If you were using jQuery...

如果您使用的是 jQuery...

$(document).on('dragover', function(evt) {
    var x = evt.pageX,
        y = evt.pageY;

    console.log(x, y);

});