Html HTML5拖放以在屏幕上的任何位置移动div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7278409/
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 drag and drop to move a div anywhere on the screen?
提问by lisovaccaro
The title is pretty self explanatory.
标题是不言自明的。
All the demos I've found consist in dropping a div to a certain location. E.G a trashcan. I need to make a draggable div that can be dropped anywhere on the screen.
我发现的所有演示都包括将 div 放到某个位置。EG垃圾桶。我需要制作一个可拖放的 div,它可以放在屏幕上的任何地方。
Is it possible to do this with HTML5? if not how should I do it?
可以用 HTML5 做到这一点吗?如果不是我该怎么做?
回答by robertc
It's quite straightforward really:
这真的很简单:
- In the
dragstart
event calculate the offset between where the user clicked on the draggable element and the top left corner - Make sure the
dragover
event is applied to the entire document so the element can be dropped anywhere - In the
drop
event, use the offset you calculated with theclientX
andclientY
of the drop to work out where to position the element
- 在
dragstart
事件中计算用户单击可拖动元素的位置与左上角之间的偏移量 - 确保
dragover
事件应用于整个文档,以便可以将元素放置在任何地方 - 在这种情况
drop
下,使用您通过下落的clientX
和计算的偏移量clientY
来确定元素的位置
Here's oneI prepared earlier. For bonus points you can update the top and left position of the element in the dragover event, this is useful if the bit you're allowing to be dragged isn't the whole element that needs to be moved.
这是我之前准备的。对于奖励积分,您可以在dragover 事件中更新元素的顶部和左侧位置,如果您允许拖动的位不是需要移动的整个元素,这将非常有用。