search
HomeWeb Front-endH5 TutorialExample explanation of HTML5 DragEvent interface

DragEvent is a DOM event interface that represents the interaction between drag and drop. The user starts dragging by placing a pointing device (such as a mouse) on the target's surface, and then drags the pointer to a new location (such as another DOM element). The application automatically resolves drag-and-drop interactions. The DragEvent interface inherits properties from mouseEvent and Event.

Event types

DragEvent is not a single event, it contains multiple events, these events are: drag, dragstart, dragenter, dragend, dragover, dragexit, dragleave , drop.

drag: This event is triggered repeatedly during the dragging process of the element, once every 100 milliseconds. The target element of this event is the dragged element. This event can bubble up and cancel the default behavior.

dragstart: This event is triggered when the user starts dragging. The target element of this event is the element being dragged. Among these events, the dragstart event is triggered first. This event can bubble up and cancel the default behavior.

dragenter: This event is triggered when the dragged element enters a legal droppable target. The target element of this event is the droppable target. This event can bubble up and cancel the default behavior.

dragover: This event is triggered repeatedly when the dragged element moves within the drop target range, once every 100 milliseconds. The target element of this event is the droppable target. This event can bubble up and cancel the default behavior.

dragend: This event is triggered when dragging ends. The target element of this event is the dragged element. Dragend fires last among these events. This event can bubble up and cannot cancel the default behavior.

dragleave: This event is triggered when the dragged element leaves a legal droppable target. The target element of this event is the droppable target. This event can bubble up and cannot cancel the default behavior.

dragexit: This event is triggered when a droppable element is no longer the nearest drop target of the drag operation. The target element of this event is the droppable element. This event can bubble up and will not cancel the default behavior.

drop: This event is triggered when the pointer device of the dragged element is released on the dropable target. The target element of this event is the droppable target. The drop event fires before the dragend event fires. This event can bubble up and cancel the default behavior.

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>test target</title>
    <style type="text/css">
        #drag{
            width:200px;
            height:200px;
            background-color: aqua;
        }
        .drop{
            width: 300px;
            height: 300px;
            background-color: antiquewhite;
        }
    </style>
</head>
<body>
    <p id="drag" draggable="true" ondragstart="event.dataTransfer.setData(&#39;text/plain&#39;,&#39;dddd&#39;)">
        我可以拖动
    </p>
    <img  src="/static/imghwm/default1.png"  data-src="test.jpg"  class="lazy"   id="img" alt="Example explanation of HTML5 DragEvent interface" >
    <p class="drop"></p>
    <script type="text/javascript">
        document.addEventListener(&#39;drag&#39;,function(event){
            event.target.style.backgroundColor = &#39;black&#39;;
        },false);
        document.addEventListener(&#39;dragstart&#39;,function(event){
            event.target.style.backgroundColor = &#39;red&#39;;

        },false);
        document.addEventListener(&#39;dragend&#39;,function(event){
            event.target.style.backgroundColor = &#39;yellow&#39;;
        },false);
        document.addEventListener(&#39;dragover&#39;,function(event){
            event.preventDefault();
            event.target.style.backgroundColor = &#39;blue&#39;;
        },false);
        document.addEventListener(&#39;dragenter&#39;,function(event){
            event.target.style.backgroundColor = &#39;green&#39;;
        },false);
        document.addEventListener(&#39;dragleave&#39;,function(event){
            event.target.style.backgroundColor = &#39;pink&#39;;
        },false);
        document.addEventListener(&#39;dragexit&#39;,function(event){
            event.target.style.backgroundColor = &#39;red&#39;
        },false);
        document.addEventListener(&#39;drop&#39;,function(event){
            event.preventDefault();
            event.target.style.backgroundColor = &#39;white&#39;;
            console.log(2);


        },false)
    </script>
</body>
</html>

The event objects of these events contain the methods and properties of the event objects of mouse events. In addition, there is also a dataTransfer attribute

making the element draggable

In HTML, the only draggable elements by default are image, link and selected text. To make other elements draggable, you need to do the following three things:

1. Set a draggable attribute to the element, and set the value of this attribute to true

2. In this element Add a dragstart event listener

3. Set the drag data on the dragstart event listener through event.DataTransfer.setData(type, value).

<p draggable="true" ondragstart="event.dataTransfer.setData(&#39;text/plain&#39;, &#39;This text may be dragged&#39;)">
      This text <strong>may</strong> be dragged.
    </p>

If the draggable attribute is disabled or set to false, then this element cannot be dragged. The draggable attribute can be set on any property. When an element is set to draggable, clicking or dragging the mouse on the element will not select the text or other elements in the element. When the user starts dragging, the dragstart event will be triggered. In the dragstart event, you can specify the drag data through setData(), specify the image feedback through setDragImage(), and specify the drag effect by setting the effectAllowed attribute and dropEffect attribute. Drag data must be specified, but the picture feedback is that the drag effect is not necessary

Drag data

Drag data contains two parts of information, namely the type of data and the value of the data , the data type is String, and the data value is also in the form of a string. The types of drag and drop data include: text/plain, text/html, image/jpeg, text/uri-list, etc. You can also customize the type.

You can call the setData() method multiple times to set multiple drag and drop data. As follows:

var dt = event.dataTransfer;
dt.setData("application/x-bookmark",bookmarkString);
dt.setData(&#39;text/uri-list&#39;,&#39;www.baidu.com&#39;);
dt.setData(&#39;text/plain&#39;,&#39;drag data&#39;);

application/x-bookmark is a custom type.

If you set a new type of data through this method, then the new drag data will be at the end of the drag data list. If you set the existing type of data, then the new data will overwrite the old one. data.

The specified type of drag and drop data can be obtained through getData()

The specified type of drag and drop data can be cleared through clearData()

Picture feedback

Image feedback does not have to be set. By default, it is a translucent image generated from the drag target, and this image will follow the mouse movement during dragging. You can customize image feedback through the setDragImage(image,xOffect,yOffect) method.

setDragImage() accepts three parameters. The first parameter represents the picture reference , and the second and third parameters represent the position of the upper left corner of the picture relative to the mouse pointer. The unit is pixels

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>test target</title>
    <style type="text/css">
        #drag{
            width:200px;
            height:200px;
            background-color: aqua;
        }
        .drop{
            width: 300px;
            height: 300px;
            background-color: antiquewhite;
        }
    </style>
</head>
<body>
    <p id="drag" draggable="true" ondragstart="event.dataTransfer.setData(&#39;text/plain&#39;,&#39;dddd&#39;)">
        我可以拖动
    </p>
    <img  src="/static/imghwm/default1.png"  data-src="test.jpg"  class="lazy"   id="img" alt="Example explanation of HTML5 DragEvent interface" >
    <p class="drop"></p>
    <script type="text/javascript">
      
        document.addEventListener(&#39;dragstart&#39;,function(event){
            event.target.style.backgroundColor = &#39;red&#39;;
            event.dataTransfer.setDragImage(document.getElementById(&#39;img&#39;),30,30);

        },false);
       
    </script>
</body>
</html>

Drag effect

You can specify the drag effect by setting effectAllowed and dropEffect

事件对象的dataTransfer属性

dataTransfer属性是一个DataTransfer对象,在这个属性中保存了拖拽操作过程中的数据,它可能保存一个或者多个数据项。这个属性是只读的。

dataTransfer属性中的标准属性

1.dropEffect

得到当前drag and drop操作的类型,或者设置给当前drag and drop 设置新的类型。这个属性可能取值是none,copy,move,link。这属性会影响拖拽过程中的鼠标的显示形式。

2.effectAllowed

这个属性用于指定运行的拖拽操作效果,可选的值有none,all,copy,move,link,copyLink,copyMove,linkMove。默认情况这个值是all,如果要设置这个属性的值就要在dragstart的事件处理程序里进行设置。

3.files

包含了在data transfer中的所有可用的本地文件列表,如果被拖拽操作没有涉及文件,那么它是一个空列表。

4.items

是一个包含了所有拖拽数据的列表。它是一个DataTransferItemList对象。

5.types

它是一个字符串数组,这个数组中包含在dragstart事件处理程序中设置的拖拽事件的类型,如果拖拽操作不存在数据,那么他得到一个空数组。

DataTransfer属性的标准方法

1.clearData(type):移除给定类型相关的拖拽数据。接受一个可选的参数,如果这个参数是空或者没有指定,那么移除所以类型的数据,如果指定的类型不存在或者data transfer中不包含数据,那么这个方法不会产生什么影响。

2.getData(type):得到指定类型的拖拽数据。如果指定类型的数据不存在或者data transfer中不包含数据, 得到一个空的字符串。

3.setData(type,value):设置给定类型的拖拽数据。接受两个参数,第一个参数是类型,第二个参数是指定类型的值。 如果这个类型的值不存在,那么在类型列表的最后添加一个新的格式,如果已经存在的,那么在相同的位置 存在的数据被替换.

4.setDragImage(image,xoffset,yoffset):接受三个参数,第一个参数是图片的引用,第二个和第三个参数是移动的图片的 左上角相对鼠标的位置。

DataTransferList对象

通过dataTransfer.items得到的值就是DataTransferList对象。

DataTransferList对象的属性

1.length:得到拖拽数据的数量

DataTransferList对象的方法

1.add():向拖拽数据列表中添加一个新的拖拽数据,添加成功后返回这个新的拖拽数据。当添加一个文件到拖拽数据列表中,这个方法只接受一个文件对象作为参数。当添加一个给定 类型的字符串到拖拽数据列表中,这个方法接受两个参数,第一个参数是数据,第二个参数是类型。

2.remove(index):从拖拽数据列表中移除指定位置的拖拽数据。这个方法接受一个表示位置的参数,如果这个参数小于0或者大于拖拽数据列表的长度,拖拽数据列表不会发生改变。

3.clear():移除拖拽数据列表中所有的拖拽数据。不需要参数。

4.DataTransferItem(index):得到指定位置上的拖拽数据。接受一个表示位置的参数, 这个方法简写形式是数组索引

DataTransferItem对象

dataTransfer.items中的每一项都是DataTransferItem对象。

DataTransferItem对象的属性

1.kind:得到拖拽数据的键,可能的值有file和string

2.type:得到拖拽数据的类型,是MINE type

DataTransferItem对象的方法

1.getAsFile():返回拖拽数据的文件对象。如果拖拽数据不是文件则返回null

2.getAsString(function):调用回调函数,这个回调函数将拖拽数据项的字符串形式作为它的参数

拖拽文件

要使文件能够被拖放的一个重要步骤是定义一个放置区域。并且为放置区域添加drop,dragover和dragend事件处理程序。

当为一个元素添加drop事件的处理程序,及在dragover事件处理程序中取消浏览器的默认行为,那么这个元素就是放置区域。

另外,在drag和drop操作结束之后,应用程序应该移除拖拽数据(可能是一个或者多个文件),数据的清理通常在 dragend事件处理程序中。

<p id="drop_zone" ondrop="drop_handler(event);" ondragover="dragover_handler(event);" ondragend = "dragend_handler(event)">
  <strong><Drag one or more files to this Drop Zone ...</strong>
</p>

例子一,访问文件名

function drop_handler(ev) {
  console.log("Drop");
  ev.preventDefault();
  // If dropped items aren&#39;t files, reject them
  var dt = ev.dataTransfer;
  if (dt.items) {
    // Use DataTransferItemList interface to access the file(s)
    for (var i=0; i < dt.items.length; i++) {
      if (dt.items[i].kind == "file") {
        var f = dt.items[i].getAsFile();
        console.log("... file[" + i + "].name = " + f.name);
      }
    }
  } else {
    // Use DataTransfer interface to access the file(s)
    for (var i=0; i < dt.files.length; i++) {
      console.log("... file[" + i + "].name = " + dt.files[i].name);
    }
  }
}

例子二,阻止浏览器默认行为

function dragover_handler(ev) {
  console.log("dragOver");
  // Prevent default select and drag behavior
  ev.preventDefault();
}

 例子三,清除数据

function dragend_handler(ev) {
  console.log("dragEnd");
  // Remove all of the drag data
  var dt = ev.dataTransfer;
  if (dt.items) {
    // Use DataTransferItemList interface to remove the drag data
    for (var i = 0; i < dt.items.length; i++) {
      dt.items.remove(i);
    }
  } else {
    // Use DataTransfer interface to remove the drag data
    ev.dataTransfer.clearData();
  }
}

【相关推荐】

1. 免费h5在线视频教程

2. Understand html5 in 20 minutes and see what new features H5 has.

3. Teach you how to implement an H5 micro-scene

4. Code example for making a registration page in H5

5. The difference between H5 and traditional html

6. Passed Detailed explanation of examples of H5 implementing the camera function

The above is the detailed content of Example explanation of HTML5 DragEvent interface. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Mastering Microdata: A Step-by-Step Guide for HTML5Mastering Microdata: A Step-by-Step Guide for HTML5May 14, 2025 am 12:07 AM

MicrodatainHTML5enhancesSEOanduserexperiencebyprovidingstructureddatatosearchengines.1)Useitemscope,itemtype,anditempropattributestomarkupcontentlikeproductsorevents.2)TestmicrodatawithtoolslikeGoogle'sStructuredDataTestingTool.3)ConsiderusingJSON-LD

What's New in HTML5 Forms? Exploring the New Input TypesWhat's New in HTML5 Forms? Exploring the New Input TypesMay 13, 2025 pm 03:45 PM

HTML5introducesnewinputtypesthatenhanceuserexperience,simplifydevelopment,andimproveaccessibility.1)automaticallyvalidatesemailformat.2)optimizesformobilewithanumerickeypad.3)andsimplifydateandtimeinputs,reducingtheneedforcustomsolutions.

Understanding H5: The Meaning and SignificanceUnderstanding H5: The Meaning and SignificanceMay 11, 2025 am 12:19 AM

H5 is HTML5, the fifth version of HTML. HTML5 improves the expressiveness and interactivity of web pages, introduces new features such as semantic tags, multimedia support, offline storage and Canvas drawing, and promotes the development of Web technology.

H5: Accessibility and Web Standards ComplianceH5: Accessibility and Web Standards ComplianceMay 10, 2025 am 12:21 AM

Accessibility and compliance with network standards are essential to the website. 1) Accessibility ensures that all users have equal access to the website, 2) Network standards follow to improve accessibility and consistency of the website, 3) Accessibility requires the use of semantic HTML, keyboard navigation, color contrast and alternative text, 4) Following these principles is not only a moral and legal requirement, but also amplifying user base.

What is the H5 tag in HTML?What is the H5 tag in HTML?May 09, 2025 am 12:11 AM

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

H5 Code: A Beginner's Guide to Web StructureH5 Code: A Beginner's Guide to Web StructureMay 08, 2025 am 12:15 AM

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

H5 Code Structure: Organizing Content for ReadabilityH5 Code Structure: Organizing Content for ReadabilityMay 07, 2025 am 12:06 AM

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

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.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function