拖动时获取鼠标位置(JS + HTML5) [英] Getting mouse position while dragging (JS + HTML5)

查看:965
本文介绍了拖动时获取鼠标位置(JS + HTML5)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

推荐答案

//  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);
});

下面的可运行代码段:

//	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>

这篇关于拖动时获取鼠标位置(JS + HTML5)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆