Html HTML5:dragover()、drop():如何获取当前的 x、y 坐标?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2438320/
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
HTML5: dragover(), drop(): how get current x,y coordinates?
提问by Pete Alvin
How does one determine the (x,y) coordinates while dragging "dragover" and after the drop ("drop") in HTML5 DnD?
在 HTML5 DnD 中拖动“dragover”和放下(“drop”)后,如何确定 (x,y) 坐标?
I found a webpage that describes x,y for dragover (look at e.offsetX and e.layerX to see if set for various browsers but for the life of me they ARE NOT set).
我找到了一个描述 x,y 用于拖动的网页(查看 e.offsetX 和 e.layerX 以查看是否为各种浏览器设置,但在我的生活中它们没有设置)。
What do you use for the drop(e) function to find out WHERE in the current drop target it was actually dropped?
您使用 drop(e) 函数来找出当前放置目标中实际放置的位置?
I'm writing an online circuit design app and my drop target is large.
我正在编写一个在线电路设计应用程序,我的下降目标很大。
Do I need to drop down to mouse-level to find out x,y or does HTML5 provided a higher level abstraction?
我需要下拉到鼠标级别来找出 x,y 还是 HTML5 提供了更高级别的抽象?
回答by robertc
The properties clientX
and clientY
should be set (in modern browsers):
属性clientX
和clientY
应该设置(在现代浏览器中):
function drag_over(event) {
console.log(event.clientX);
console.log(event.clientY);
event.preventDefault();
return false;
}
function drop(event) {
console.log(event.clientX);
console.log(event.clientY);
event.preventDefault();
return false;
}
Here's a (somewhat) practical examplethat works in Firefox and Chrome.
回答by Mateja Petrovic
To build on top of robertc's answer and work around the issue:
要建立在 robertc 的回答之上并解决这个问题:
The clientX and clientY are going to be inaccurate proportional to the distance of the cursor from the upper left corner of the element which was dropped.
clientX 和 clientY 将与光标与被放置的元素左上角的距离成比例不准确。
You may simply calculate the delta distance by subtracting the client coords recorded at dragStart
from the client coords recorded at dragEnd
. Bear in mind the the element which was dropped still has the exact same position at dragEnd
which you may update by the delta distance to get the new left and top positional coordinates.
你可以简单地通过减去记录在客户端COORDS计算三角洲距离dragStart
从记录在客户端COORDS dragEnd
。请记住,被丢弃的元素仍然具有完全相同的位置dragEnd
,您可以在该位置更新增量距离以获得新的左和上位置坐标。
Here's an demoin react, although the same can be accomplished in plain JS.
这是react 中的一个演示,虽然同样可以在普通 JS 中完成。