search
HomeWeb Front-endH5 TutorialDetailed explanation of H5's drag and drop function

Detailed explanation of H5's drag and drop function

Mar 27, 2018 am 09:59 AM
html5FunctionDetailed explanation

This time I will bring you a detailed explanation of the drag-and-drop function of H5. What are the precautions for implementing the drag-and-drop function of H5? The following is a practical case, let’s take a look.

About drag and drop in HTML5

Drag and drop (Drag and Drop) is a common feature, that is, grabbing an object and dragging it to another location. In HTML5, drag and drop is a standard part. In HTML5 users can use the mouse to select a draggable element, drag the element to a droppable element, and drop the element by releasing the mouse button. A translucent representation of a draggable element follows the mouse pointer during a drag operation.

If we want the element to be dragged, then we need to set its draggable attribute to true (the a tag draggable defaults to true)

Drag and drop events

Several events will be triggered at different stages of the drag-and-drop operation. The dataTransfer attribute of the drag-and-drop event stores the relevant data in the drag-and-drop operation.

dragstart Acts on [source element] and is triggered when an element starts to be dragged. The dragstart event needs to be attached to the element dragged by the user. In this event, the listener will set the information related to this drag, such as the dragged data and image.
dragenter Acts on [source element], triggered when the dragging mouse enters an element. The listener for this event needs to indicate whether the mouse is allowed to be released in this area. If no listener is set, or the listener does not operate, release is not allowed by default.
dragover Acts on [target element], triggered when the mouse during dragging moves past an element.
dragleave Acts on [target element], triggered when the dragging mouse leaves the element. Can be removed as a highlight or insertion mark that releases feedback.
drag Acts on [source element], and the event is triggered when the element is dragged.
drop Acts on [target element] and is triggered on the released element when the drag operation is completed.
dragend Acts on [source element]. The drag source is triggered when the drag operation ends, regardless of whether the operation is successful or not.

(Only drag-related events will be triggered when dragging, mouse events, such as mousemove, will not be triggered)

DataTransfer Object

When processing drag-and-drop operations, we need to use the DataTransfer object to save the dragged data. DataTransfer can save one or more pieces of data, one or more data types.
Attribute

dropEffect dropEffect
               [String] Specifies the actual placement effect, possible values:
            copy: Copy to new location
            move: Move to a new location
             link: Create a link from the source location to the new location
None: Forbidden to place (prohibited any operation)
# Effectallowed [String] Specify the allowable effect when dragging, possible values:
             copy: Copy to a new location.
              move: Move to a new location .
                                                                                                                                                                                                      link: Establish a link from the source location to the new location.
           copyLink: Allows copying or linking.
            copyMove: Allows copying or moving.
           linkMove: Allow linking or moving.
             all: Allow all operations.
​ ​ ​ none: All operations are prohibited.
​​​​​​ uninitialized: Default value (default value), equivalent to all.
files Contains a list of all local files available for data transfer. If the drag operation does not involve dragging a file, this property is an empty list.
types Save a list of types of stored data as the first item, in the same order as the data is added. If no data has been added an empty list will be returned.

Method

void addElement(Element element) Set the drag source. Usually there is no need to change this. Modifying this will affect which node is dragged and the triggering of the dragend event. The default target is the dragged node
void clearData(String type) Deletes the data associated with the given type. Type parameters are optional. If the type is empty or not specified, all data associated with the type will be deleted. This method will have no effect if the specified type of data does not exist, or if the data transfer does not contain any data.
String getData(String type) Get the data of the given type. If the data of the given type does not exist or the data dump does not contain the data, the method will return An empty string.
void setData(String type,String data) Set data for a given type. If the data type does not exist, it will be added to the end so that the last item in the type list will be the new format. If the data type already exists, replaces the existing data in the same location. That is, when replacing data of the same type, the order of the type list will not be changed.
void setDragImage(DOMElement image,long x,long y) Customize a desired drag image. In most cases, this is not necessary because the dragged node is created as a default image.
           image To be used as drag feedback image element
            x horizontal offset within the image.
y Vertical offset within the image.

Browser support

Internet Explorer 9+, Firefox, Opera 12, Chrome and Safari 5+

Demo Code

nbsp;html>


<meta>
<title>Drag & Drop</title>
<style>
.box {
    display: inline-block;
    width: 100px;
    height: 100px;
    border: 1px solid #ccccff;
    background-color: #ccccff;
    text-align: center;
    line-height: 100px;
}
.bin {
    width: 200px;
    height: 200px;
    padding: 10px;
    border: 1px solid #ccccff;
    overflow: hidden;
    float: left;
}
</style>


    <p>
        </p><p>
            </p><p>可拖拽元素</p>
        
        <p> </p>
    
    <script>
        var bins = document.querySelectorAll(&#39;.bin&#39;);
        var boxs = document.querySelectorAll(&#39;.box&#39;);
        var drag = null;
        for (var i = 0; i < boxs.length; i++) {
            var box = boxs[i];
            box.onselectstart = function() {
                return false;
            };
            box.ondragstart = function(e) {
                e.dataTransfer.effectAllowed = &#39;move&#39;;
                e.dataTransfer.setData(&#39;text/plain&#39;, e.target.outerHTML);
                e.dataTransfer.setDragImage(e.target, 0, 0);
                drag = this;
                return true;
            };
            box.ondragend = function(e) {
                drag = null;
                return false
            };
        }
        for (var i = 0; i < bins.length; i++) {
            var bin = bins[i];
            //当拖曳元素进入目标元素
            bin.ondragover = function(e) {
                e.preentDefault();
                return true;
            };
            //拖拽元素在目标元素上移动
            bin.ondragenter = function(e) {
                this.style.backgroundColor = &#39;#eeeeff&#39;;
                return true;
            };
            //拖拽元素在目标元素上离开
            bin.ondragleave = function(e) {
                this.style.backgroundColor = &#39;#fff&#39;;
                return true;
            };
            //拖拽的元素在目标元素上同时鼠标放开
            bin.ondrop = function(e) {
                if (drag) {
                    drag.parentNode.removeChild(drag);
                    this.appendChild(drag);
                }
                this.style.backgroundColor = &#39;#fff&#39;;
                return false;
            };
        }
        document.body.ondrop = function(e) {
            e.preventDefault();
            e.stopPropagation();
        }
    </script>

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of H5 synthesis poster

Drag event editor realizes drag and drop upload image effect

The above is the detailed content of Detailed explanation of H5's drag and drop function. 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
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.

H5 vs. HTML5: Clarifying the Terminology and RelationshipH5 vs. HTML5: Clarifying the Terminology and RelationshipMay 05, 2025 am 12:02 AM

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

HTML5 Features: The Core of H5HTML5 Features: The Core of H5May 04, 2025 am 12:05 AM

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

H5: Exploring the Latest Version of HTMLH5: Exploring the Latest Version of HTMLMay 03, 2025 am 12:14 AM

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

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 Tools

mPDF

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),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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