如何使用 JavaScript 从头开始​​实现拖放 div?

2022-01-11 00:00:00 drag-and-drop javascript html css

它应该是 CSS 和 JavaScript 的组合.要做的步骤应该是:

It should be a combination of CSS and JavaScript. The steps to do should be:

  1. 将其置于所有其他元素之上(指定哪个属性?)
  2. 点击事件时捕捉事件(监听哪个事件?)
  3. 在鼠标移动时移动 div.

但是细节是什么?

推荐答案

jQuery之道:

查看 jQueryUI 插件 可拖拽和可拖拽.

已经在 jQuery 框架上投入了数百个小时,以使这样的复杂任务变得微不足道.利用 jQuery 团队的努力,让我们所有人更轻松地编写丰富的跨浏览器应用程序;)

Literally hundreds of hours have been invested into the jQuery framework to make complicated tasks like this almost trivial. Take advantage of the jQuery team's efforts to make programming rich cross-browser applications easier on us all ;)

如果您坚持使用原始 javascript 进行尝试.你会想做一些事情.一,以编程方式将所有可拖动项目设置为相对/绝对定位.如果单击特定项目,请使其在 CSS 中的顶部/左侧值反映鼠标 x、y 轴所做的更改,直到释放单击为止.此外,您还需要更新每个可拖动对象的 z-index,以便在单击它以将其显示在视图中时.

If you insist on trying this with raw javascript. You'll want to do a few things. One, programmatically set all draggable items to a relative/absolute positioning. If you click a particular item, cause it's top/left values in CSS to reflect the changes made by the x,y axis of the mouse until the click is released. Additionally, you'll want to update the z-index of each draggable when it's clicked to bring it into view.

教程:如何使用 Javascript 拖放

相关文章