博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
html5: Drag and Drop
阅读量:6267 次
发布时间:2019-06-22

本文共 1996 字,大约阅读时间需要 6 分钟。

Drag and Drop

Drag and drop is a very common feature. It is when you "grab" an object and drag it to a different location.

In HTML5, drag and drop is part of the standard: Any element can be draggable.

Drag the W3Schools image into the rectangle:

Make an Element Draggable

First of all: To make an element draggable, set the draggable attribute to true: 

What to Drag - ondragstart and setData()

Then, specify what should happen when the element is dragged.

In the example above, the ondragstart attribute calls a function, drag(event), that specifies what data to be dragged.

The dataTransfer.setData() method sets the data type and the value of the dragged data:

function drag(ev) {  ev.dataTransfer.setData("text", ev.target.id);}

In this case, the data type is "text" and the value is the id of the draggable element ("drag1").

Where to Drop - ondragover

The ondragover event specifies where the dragged data can be dropped.

By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element.

This is done by calling the event.preventDefault() method for the ondragover event

Do the Drop - ondrop

When the dragged data is dropped, a drop event occurs.

In the example above, the ondrop attribute calls a function, drop(event):

function drop(ev) {  ev.preventDefault();  var data = ev.dataTransfer.getData("text");  ev.target.appendChild(document.getElementById(data));}

Code explained:

  • Call preventDefault() to prevent the browser default handling of the data (default is open as link on drop)
  • Get the dragged data with the dataTransfer.getData() method. This method will return any data that was set to the same type in the setData() method
  • The dragged data is the id of the dragged element ("drag1")
  • Append the dragged element into the drop element

Drag and Drop

Drag the image back and forth between the two div elements.

 

 

转载于:https://www.cnblogs.com/Nyan-Workflow-FC/p/10717632.html

你可能感兴趣的文章
Enumberable
查看>>
开发者论坛一周精粹(第五十四期) 求购备案服务号1枚!
查看>>
validate表单验证及自定义方法
查看>>
javascript 中出现missing ) after argument list的错误
查看>>
使用Swagger2构建强大的RESTful API文档(2)(二十三)
查看>>
Docker容器启动报WARNING: IPv4 forwarding is disabled. Networking will not work
查看>>
(转)第三方支付参与者
查看>>
程序员修炼之道读后感2
查看>>
DWR实现服务器向客户端推送消息
查看>>
js中forEach的用法
查看>>
Docker之功能汇总
查看>>
!!a标签和button按钮只允许点击一次,防止重复提交
查看>>
(轉貼) Eclipse + CDT + MinGW 安裝方法 (C/C++) (gcc) (g++) (OS) (Windows)
查看>>
还原数据库
查看>>
作业调度框架 Quartz.NET 2.0 beta 发布
查看>>
mysql性能的检查和调优方法
查看>>
项目管理中的导向性
查看>>
Android WebView 学习
查看>>
(转)从给定的文本中,查找其中最长的重复子字符串的问题
查看>>
HDU 2159
查看>>