博客
关于我
强烈建议你试试无所不能的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

你可能感兴趣的文章
8Manage:企业管理软件要通用型还是定制开发?
查看>>
吴恩达朋友圈宣布“喜讯”:AI专家王冬岩加入Landing AI ...
查看>>
乐行科技获1.08亿元A轮融资,并推出艾特好车
查看>>
云计算,能回答地球最终流浪到哪里吗?
查看>>
Oracle三级联动单表地址数据
查看>>
数据快传对于企业的重要性!
查看>>
《2018-2019全球IPv6支持度白皮书》发布,江北新区IPv6示范区建设正式启动
查看>>
策略模式原来这么简单!
查看>>
char,Character,int,字符及编码日记
查看>>
Data Structure_Sort Algorithm
查看>>
Linux下区分物理CPU、逻辑CPU和CPU核数
查看>>
EDAS ScheduleX 问题
查看>>
Android 表格HorizontalScrollView+ListView
查看>>
mybatis 联查
查看>>
如何使用阿里云服务器
查看>>
科创板7天受理28家公司,但后者“含金量”备受质疑
查看>>
交通运输部部长李小鹏谈及自动驾驶:包容失败、反对垄断,力争在国家层面出台指导意见...
查看>>
退市35年后,牛仔裤品牌李维斯要重新IPO了
查看>>
PHP 7.3声称速度比PHP 5快3倍还多,值得更新了!
查看>>
elasticsearch使用指南之Elasticsearch Document Index API详解、原理与示例
查看>>