HTML5拖放在屏幕上的任何位置移动div? [英] HTML5 drag and drop to move a div anywhere on the screen?

查看:605
本文介绍了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?

推荐答案

真的很简单:


  1. dragstart 事件中,计算用户点击可拖动元素和左上角之间的偏移量

  2. 确保将拖动事件应用于整个文档,以便元素可以在任何位置被删除

  3. drop 事件,使用您使用 clientX clientY
  1. In the dragstart event calculate the offset between where the user clicked on the draggable element and the top left corner
  2. Make sure the dragover event is applied to the entire document so the element can be dropped anywhere
  3. In the drop event, use the offset you calculated with the clientX and clientY 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.

这篇关于HTML5拖放在屏幕上的任何位置移动div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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