HTML5拖放以将div移动到屏幕上的任何位置?
标题很清楚.
我发现的所有演示都包括将 div 放到某个位置.例如垃圾桶.我需要制作一个可拖动的 div,它可以放在屏幕上的任何位置.
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.
HTML5 可以做到这一点吗?如果不是我应该怎么做?
Is it possible to do this with HTML5? if not how should I do it?
推荐答案
真的很简单:
- 在
dragstart
事件中计算用户点击可拖动元素的位置与左上角之间的偏移量 - 确保将
dragover
事件应用于整个文档,以便可以将元素拖放到任何地方 - 在
drop
事件中,使用您使用 drop 的clientX
和clientY
计算出的偏移量来计算元素的位置
- 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
这是一个 我 早前准备.对于奖励积分,您可以在 中更新元素的顶部和左侧位置dragover 事件,如果您允许拖动的位不是需要移动的整个元素,这很有用.
Here's one I 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.
相关文章