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

查看:23
本文介绍了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. 确保将 dragover 事件应用于整个文档,以便可以将元素拖放到任何地方
  3. drop 事件中,使用您使用 drop 的 clientXclientY 计算出的偏移量来计算元素的位置
  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天全站免登陆