This time I will bring you a detailed explanation of H5 Drag and Drop. What are the precautions when using H5 Drag and Drop? What are the practical cases below? Let’s take a look.
Introduction
Drag-and-drop is a common feature where you grab an object and then drag it to another location. In HTML5, drag and drop is part of the standard, and any element can be dragged and dropped. First click on a small example: execute when the user starts dragging theelement
<p>拖动我!</p>Tips: Links and images are draggable by default. The draggable attribute is not required.
Definition and usage
The following events will be triggered during the drag and drop process:- Triggered on the drag target Event (source element): ondragstart - Fires when the user starts dragging the element
- ondrag - Fires when the element is being dragged
- ondragend - Triggered after the user completes dragging the element
- Event triggered when the target is released: ondragenter -This event is triggered when the object dragged by the mouse enters its container scope
- ondragover - This event is triggered when a dragged object is dragged within the scope of another object container
- ondragleave - This event is triggered when the object being dragged by the mouse leaves the scope of its container
- ondrop - This event is triggered when the mouse button is released during a dragging process
Browser support
Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support dragging. Note: Safari 5.1.2 does not support dragging; when dragging an element, the ondragover event will be triggered every 350 milliseconds.Example
First paste the code, and then explain one by one:nbsp;html> <title>HTML5拖拽</title> <meta> <style> #p1 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;} </style> <p>拖动img_w3slogo.gif图片到矩形框中:</p> <p></p> <br> <img src="/static/imghwm/default1.png" data-src="images/img_w3slogo.gif" class="lazy" alt="Detailed explanation of H5 Drag and Drop" > <script> function allowDrop(ev){ ev.preventDefault(); } function drag(ev){ ev.dataTransfer.setData("Text",ev.target.id); } function drop(ev){ ev.preventDefault(); var data=ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); } </script>The page effect before dragging is:
Set the element to be draggable
First, in order to make the element draggable, set the draggable attribute to true:<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/7d36d626635b37edacf6fb28e221a32c-1.png?x-oss-process=image/resize,p_40" class="lazy" alt="Detailed explanation of H5 Drag and Drop" >
Drag What to move - ondragstart and setData()
Then, specify what happens when the element is dragged. In the above example, the ondragstart attribute calls a function, drag(event), which specifies the data to be dragged. dataTransfer.setData() method sets thedata type and value of the dragged data:
function drag(ev) { ev.dataTransfer.setData("Text",ev.target.id); }In this example, the data type is "Text" and the value is The id of the dragged element ("drag1").
Where to place - ondragover
ondragover event specifies where to place the dragged data. By default, data/elements cannot be placed into other elements. If we need to allow placement, we must prevent the default handling of the element. This is done by calling the event.preventDefault() method of the ondragover event:event.preventDefault()
for placement - ondrop
When the dragged data is placed, A drop event will occur. In the above example, 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 explanation:
- Call preventDefault() To avoid the browser's default processing of data (the default behavior of the drop event is to open it as a link)
- Get the dragged data through the dataTransfer.getData("Text") method. This method will return any data set to the same type in the setData() method.
- The dragged data is the id of the dragged element ("drag1")
- Append the dragged element to the placement element (target element) The result of
dataTransfer对象
在拖曳操作的过程中,我们可以用过dataTransfer对象来传输数据,以便在拖曳操作结束的时候对数据进行其他的操作。
对象属性:
dropEffect:设置或返回拖放目标上允许发生的拖放行为。如果此处设置的拖放行为不再effectAllowed属性设置的多种拖放行为之内,拖放操作将会失败。该属性值只允许为“null”、“copy”、“link”和“move”四值之一。
effectAllowed:设置或返回被拖动元素允许发生的拖动行为。该属性值可设为“none”、“copy”、“copyLink”、“copyMove”、“link”、“linkMove”、“move”、“all”和“uninitialized”。
items:该属性返回DataTransferItems对象,该对象代表了拖动数据。
types:该属性返回一个DOMStringList对象,该对象包括了存入dataTransfer中数据的所有类型。
对象方法:
setData(format,data):将指定格式的数据赋值给dataTransfer对象,参数format定义数据的格式也就是数据的类型,data为待赋值的数据
getData(format):从dataTransfer对象中获取指定格式的数据,format代表数据格式,data为数据。
clearData([format]):从dataTransfer对象中删除指定格式的数据,参数可选,若不给出,则为删除对象中所有的数据。
addElement(element):添加自定义图标
setDragImage(element,x,y):设置拖放操作的自定义图标。其中element设置自定义图标,x设置图标与鼠标在水平方向上的距离,y设置图标与鼠标在垂直方向上的距离。
Identify what is draggable
function dragstart_handler(ev) { console.log("dragStart"); // Add the target element's id to the data transfer object ev.dataTransfer.setData("text/plain", ev.target.id); } <p>This element is draggable.</p>
Define the drag's data
function dragstart_handler(ev) { // Add the drag data ev.dataTransfer.setData("text/plain", ev.target.id); ev.dataTransfer.setData("text/html", "<p>Example paragraph</p>"); ev.dataTransfer.setData("text/uri-list", "http://developer.mozilla.org"); }
Define the drag image
function dragstart_handler(ev) { // Create an image and then use it for the drag image. // NOTE: change "example.gif" to an existing image or the image // will not be created and the default drag image will be used. var img = new Image(); img.src = 'example.gif'; ev.dataTransfer.setDragImage(img, 10, 10); }
Define the drag effect
function dragstart_handler(ev) { // Set the drag effect to copy ev.dataTransfer.dropEffect = "copy"; }
Define a drop zone
function dragover_handler(ev) { ev.preventDefault(); // Set the dropEffect to move ev.dataTransfer.dropEffect = "move" } function drop_handler(ev) { ev.preventDefault(); // Get the id of the target and add the moved element to the target's DOM var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } <p>Drop Zone</p>
火狐浏览器拖拽问题
但是进行到这儿在火狐浏览器中发现一个问题:
html5的拖拽,用了preventDefault防止弹出新页面,但在火狐下不管用?
解决办法:
document.body.ondrop = function (event) { event.preventDefault(); event.stopPropagation(); }
或者对于上面的实例中,添加到ondrop方法里面也是可以的:
function drop(ev){ ev.preventDefault(); ev.stopPropagation(); var data=ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); }
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of H5 Drag and Drop. For more information, please follow other related articles on the PHP Chinese website!

html5的div元素默认一行不可以放两个。div是一个块级元素,一个元素会独占一行,两个div默认无法在同一行显示;但可以通过给div元素添加“display:inline;”样式,将其转为行内元素,就可以实现多个div在同一行显示了。

html5中列表和表格的区别:1、表格主要是用于显示数据的,而列表主要是用于给数据进行布局;2、表格是使用table标签配合tr、td、th等标签进行定义的,列表是利用li标签配合ol、ul等标签进行定义的。

固定方法:1、使用header标签定义文档头部内容,并添加“position:fixed;top:0;”样式让其固定不动;2、使用footer标签定义尾部内容,并添加“position: fixed;bottom: 0;”样式让其固定不动。

html5中不支持的标签有:1、acronym,用于定义首字母缩写,可用abbr替代;2、basefont,可利用css样式替代;3、applet,可用object替代;4、dir,定义目录列表,可用ul替代;5、big,定义大号文本等等。

HTML5中画布标签是“<canvas>”。canvas标签用于图形的绘制,它只是一个矩形的图形容器,绘制图形必须通过脚本(通常是JavaScript)来完成;开发者可利用多种js方法来在canvas中绘制路径、盒、圆、字符以及添加图像等。

html5废弃了dir列表标签。dir标签被用来定义目录列表,一般和li标签配合使用,在dir标签对中通过li标签来设置列表项,语法“<dir><li>列表项值</li>...</dir>”。HTML5已经不支持dir,可使用ul标签取代。

3种取消方法:1、给td元素添加“border:none”无边框样式即可,语法“td{border:none}”。2、给td元素添加“border:0”样式,语法“td{border:0;}”,将td边框的宽度设置为0即可。3、给td元素添加“border:transparent”样式,语法“td{border:transparent;}”,将td边框的颜色设置为透明即可。

因为html5不基于SGML(标准通用置标语言),不需要对DTD进行引用,但是需要doctype来规范浏览器的行为,也即按照正常的方式来运行,因此html5只需要写doctype即可。“!DOCTYPE”是一种标准通用标记语言的文档类型声明,用于告诉浏览器编写页面所用的标记的版本。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.