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

你可能感兴趣的文章
Delphi IdTCPClient IdTCPServer 点对点传送文件
查看>>
Delphi中使用ActiveX的一些心得
查看>>
QT5.8.0+MSVC2015安装以及环境配置(不需要安装VS2015)
查看>>
(原創) C/C++的function prototype和header file (C/C++) (C)
查看>>
深入理解JavaScript系列(29):设计模式之装饰者模式
查看>>
程序员的罪与罚
查看>>
SQL*LOADER错误总结
查看>>
SQL日志收缩
查看>>
【转】MySQL Query Cache 小结
查看>>
SVN分支和合并的简单例子
查看>>
PHP实现的封装验证码类
查看>>
Augular初探
查看>>
PHPStorm下XDebug配置
查看>>
【LeetCode】55. Jump Game
查看>>
Android应用盈利广告平台的嵌入方法详解
查看>>
Linux(CentOS6.5) 开放端口,配置防火墙
查看>>
Func与Action
查看>>
Android ViewPager 应该及技巧
查看>>
ODI KM二次开发手册
查看>>
iOS通讯录整合,兼容iOS789写法,附demo
查看>>