HTML5 drag and drop to move a div anywhere on the screen?(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
dragstartevent calculate the offset between where the user clicked on the draggable element and the top left corner - Make sure the
dragoverevent is applied to the entire document so the element can be dropped anywhere - In the
dropevent, use the offset you calculated with theclientXandclientYof 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.
这篇关于HTML5拖放以将div移动到屏幕上的任何位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:HTML5拖放以将div移动到屏幕上的任何位置?
基础教程推荐
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
