Table of Contents
 四、关于拖放数据传递
五、总结
Home Web Front-end H5 Tutorial H5 drag and drop API basics

H5 drag and drop API basics

May 28, 2017 am 11:07 AM

Make no mistake, this article is not about how to mop the floor. Friends who have read "javascriptEssence" should know that the process of implementing drag and drop is relatively complicated. Times are different now. We can use H5's new drag and dropAPI It is very convenient to realize the drag and drop effect. Recently, I met a fellow gardener in the garden who wrote an article "HTML5 Advanced Series: Drag-and-Drop API to Realize Drag-and-Drop Sorting". It is really the work of a master. Mr. Xiong, as a newbie (not a master), I can't compare with it, so I launched the basic chapter. I hope all garden friends will gain something from it.

1. A simple example--pick up a few pebbles on the ground

 


    地上有石子,捡几个吧
    
    
        
        
        
    
    
    我是篮子    
    
    我是地
    
        石子
        石子
        石子
        石子
        石子
        石子
        石子
        石子
        石子
        石子
Copy after login


 (g

if The demonstration is using edge. It is too troublesome to make gif on my ubuntu, so I borrowed a windows)

 

 Here is a simple one The example demonstrates how to implement drag and drop, so here comes the question. From the above demonstration, you can guess the usage of some

properties and methods. What are the functions of those methods? What do those attributes mean? Come one by one below.

2. General steps to implement drag and drop

1. Find a draggable element

Just as not everyone is called Big Bear, and Not all elements can be dragged. The img and a elements are draggable by default, and other elements are not draggable by default. At that time, you can add draggable=true to make it draggable.

 


<p draggable=&#39;true&#39;></p>
Copy after login


 

2. Handle drag-and-drop related events

All related events are as follows: (This is taken from: http://www.cnblogs.com/linxin/p/6794542.html)

Source

Object :

Process object:

  • dragenter: The source object begins to enter the scope of the process object.

  • dragover: The source object moves within the scope of the process object.

  • dragleave: The source object leaves the scope of the procedure object.

Target object:

  • drop: The source object is dragged and dropped into the target object.

We can use a test to see when these events are triggered and what the event objects are.

 


<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>testEvents</title>
    <style type="text/css">
        .source{
            width: 50px;
            height: 50px;
            border: 1px solid red;
        }
        .process{
            width: 100px;
            height: 100px;
            border: 1px solid black;
            margin-top: 10px;
        }
        .dest{
            width: 100px;
            height: 100px;
            border: 1px solid green;
            margin-top: 10px;
        }
    </style></head><body>
    <p class="source" id="source" draggable="true"></p>
    <p class="process" id="process"></p>
    <p class="dest" id="dest"></p>
    <script type="text/javascript">
    window.onload=function(){        var source = document.getElementById("source");        var process = document.getElementById("process");        var dest = document.getElementById("dest");        var sourceEle;

        source.addEventListener("dragstart",function(e){
            console.log("source dragstart");
            console.log(e);
            sourceEle = e.target;            var dt = e.dataTransfer;
            dt.effectedAllowed = "all";
        },false);

        process.addEventListener("dragenter",function(e){
            console.log("process dragenter");
            console.log(e);
        },false);

        process.addEventListener("dragover",function(e){
            console.log("process dragover");
            console.log(e);
        },false);

        process.addEventListener("dragleave",function(e){
            console.log("process dragleave");
            console.log(e);
        },false);

        source.addEventListener("drag",function(e){
            console.log("source drag");
            console.log(e);
        },false);

        dest.addEventListener("dragend",function(e){
            console.log("dest dragend");
            console.log(e);
            e.preventDefault();
        },false);

        dest.addEventListener("drop",function(e){
            console.log("dest drop");
            console.log(e);
            dest.appendChild(sourceEle);
            e.preventDefault();
            e.stopPropagation();
        },false);

        document.ondragover = function(e){e.preventDefault();}
        document.ondrop = function(e){e.preventDefault();}
    }    </script></body></html>
Copy after login


This example lists the events involved in the drag-and-drop process, which will not be detailed here. Speaking of which, you can check the console to see the order in which events are triggered and the event objects.

3. An important object DataTransfer object

The first letter here is capitalized. Strictly speaking, it is called a class. Each drag and drop will instantiate this class and save it in the dataTransfer attribute of the event object. . Its attributes and methods are shown in the table below (from: http://www.cnblogs.com/ijjyo/p/4316232.html)

Thank you for your summary, I have taken so many things from you, thank you ah.

 

 

 

   

 

Let’s do some simple tests

 

About effectAllowed and dropEffect, here the former is set to effectAllowed and the latter is selected using the drop-down list so that different mouse styles can be seen.

 


<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>testEvents</title>
    <style type="text/css">
        .source{
            width: 50px;
            height: 50px;
            border: 1px solid red;
        }
        .process{
            width: 100px;
            height: 100px;
            border: 1px solid black;
            margin-top: 10px;
        }
        .dest{
            width: 100px;
            height: 100px;
            border: 1px solid green;
            margin-top: 10px;
        }
    </style></head><body>
    <select id="dpe">
        <option value="copy">copy</option>
        <option value="move">move</option>
        <option value="link">link</option>
        <option value="none">none</option>
    </select>
    <p class="source" id="source" draggable="true"></p>
    <p class="process" id="process"></p>
    <p class="dest" id="dest"></p>
    <script type="text/javascript">
    window.onload=function(){        var source = document.getElementById("source");        var process = document.getElementById("process");        var dest = document.getElementById("dest");        var dpe = document.getElementById("dpe");        var dpev;

        dpe.onchange = function(){
            dpev = this.value;
        }        var sourceEle;

        source.addEventListener("dragstart",function(e){
            console.log("source dragstart");
            console.log(e);
            sourceEle = e.target;            var dt = e.dataTransfer;
            dt.effectedAllowed = "all";
        },false);

        dest.addEventListener("dragend",function(e){
            console.log("dest dragend");
            console.log(e);
            e.preventDefault();
        },false);

        dest.addEventListener("drop",function(e){
            console.log("dest drop");
            console.log(e);
            dest.appendChild(sourceEle);
            e.preventDefault();
            e.stopPropagation();
        },false);

        document.ondragover = function(e){
            e.dataTransfer.dropEffect = dpev;
            e.preventDefault();
        }
        document.ondrop = function(e){e.preventDefault();}
    }    </script></body></html>
Copy after login


I tested the method on ubuntu

chr#ome and found that it is all the same , but it cannot be dragged in when it is set to none. There may be some differences in different systems.

 

About the setData() and getData() methods

These two are methods related to data exchange. The former passes two parameters, and the first parameter is a mime type.

String, the second one is data; the latter passes a parameter, which is mime type. Available mime types are text/plain, text/html, text/xml, text/uri-list.

Test case, drag the menu item onto the notebook.

 


<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>点菜</title>
    <style type="text/css">
        .menu{
            width: 200px;
            height: 300px;
            border: 1px solid red;
            margin-right: 10px;
            float: left;
        }
        .record{
            width: 200px;
            height: 300px;
            border: 1px solid black;
            margin-right: 10px;
            float: left;
        }
    </style></head><body>
    <ul class="menu" id="menu">
        <li draggable="true">糖醋排骨</li>
        <li draggable="true">青椒肉丝</li>
        <li draggable="true">武昌鱼</li>
        <li draggable="true">手撕包材</li>
        <li draggable="true">千叶豆腐</li>    
    </ul>
    <ul class="record" id="record">
        
    </ul>
    <script type="text/javascript">
        window.onload = function(){            var menu = document.getElementById("menu");            var record = document.getElementById("record");

            menu.addEventListener("dragstart",function(e){                var dt = e.dataTransfer;                var tar = e.target;                if(tar.tagName=="LI"){
                    dt.setData("text/plain",tar.innerHTML);
                }
                dt.effectedAllowed = "all";
            },false);

            record.addEventListener("drop",function(e){                var li  = document.createElement("li");
                li.appendChild(document.createTextNode(e.dataTransfer.getData("text/plain")));
                record.appendChild(li);
                e.stopPropagation();
            },false);

            record.addEventListener("dropend",function(e){
                e.preventDefault();
            },false);

            document.addEventListener("dragover",function(e){e.preventDefault()},false);

            document.addEventListener("drop",function(e){e.preventDefault()},false);
        }    </script></body></html>
Copy after login


  关于setDragImage(Element img,long x,long y)

   这个方法是设置拖放时的图标的,第一个参数表是图标元素,第二个表示相对与光标的水平偏移,第三个是垂直的。

  还是前面的例子,在dragstart事件添加下面的代码,拖动时你会发现一只很大的手(不要被吓到);


var img = document.createElement("img");
                img.src = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1493802056263&di=232de2c30491e19f32833669ad5a67ae&imgtype=0&src=http%3A%2F%2Fstatic.freepik.com%2Ffree-photo%2Fone-finger_318-10333.jpg";
                dt.setDragImage(img,10,10);
Copy after login


 

 四、关于拖放数据传递

  上面的例子已经谈到了拖放的数据传递方法,这里在总结一下。

  1、通过dataTransfer的setData()和getData()方法传递

  2、通过闭包的方法,请参考开篇的例子。

五、总结

  HTML5的拖放api非常简洁实用,为我们省去了很多麻烦,如果没有它,我们可能需要通过mousedownmousemove等等事件才能实现上述功能。本文较为详细的介绍了相关api,希望对你有所帮助。关于拖放api的应用大家可以参看下面链接的文章,他做了一个拖放排序,这是一个比较常见的应用场景。

  大~熊同学的粉丝数正在逼近三位数,感谢各位园友的支持,大~熊会继续努力的! 

  参考:

  • http://www.cnblogs.com/ijjyo/p/4316232.html 

  • http://www.cnblogs.com/linxin/p/6794542.html

 

 

The above is the detailed content of H5 drag and drop API basics. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to run the h5 project How to run the h5 project Apr 06, 2025 pm 12:21 PM

Running the H5 project requires the following steps: installing necessary tools such as web server, Node.js, development tools, etc. Build a development environment, create project folders, initialize projects, and write code. Start the development server and run the command using the command line. Preview the project in your browser and enter the development server URL. Publish projects, optimize code, deploy projects, and set up web server configuration.

What exactly does H5 page production mean? What exactly does H5 page production mean? Apr 06, 2025 am 07:18 AM

H5 page production refers to the creation of cross-platform compatible web pages using technologies such as HTML5, CSS3 and JavaScript. Its core lies in the browser's parsing code, rendering structure, style and interactive functions. Common technologies include animation effects, responsive design, and data interaction. To avoid errors, developers should be debugged; performance optimization and best practices include image format optimization, request reduction and code specifications, etc. to improve loading speed and code quality.

How to make h5 click icon How to make h5 click icon Apr 06, 2025 pm 12:15 PM

The steps to create an H5 click icon include: preparing a square source image in the image editing software. Add interactivity in the H5 editor and set the click event. Create a hotspot that covers the entire icon. Set the action of click events, such as jumping to the page or triggering animation. Export H5 documents as HTML, CSS, and JavaScript files. Deploy the exported files to a website or other platform.

What Does H5 Refer To? Exploring the Context What Does H5 Refer To? Exploring the Context Apr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

What application scenarios are suitable for H5 page production What application scenarios are suitable for H5 page production Apr 05, 2025 pm 11:36 PM

H5 (HTML5) is suitable for lightweight applications, such as marketing campaign pages, product display pages and corporate promotion micro-websites. Its advantages lie in cross-platformity and rich interactivity, but its limitations lie in complex interactions and animations, local resource access and offline capabilities.

What is the H5 programming language? What is the H5 programming language? Apr 03, 2025 am 12:16 AM

H5 is not a standalone programming language, but a collection of HTML5, CSS3 and JavaScript for building modern web applications. 1. HTML5 defines the web page structure and content, and provides new tags and APIs. 2. CSS3 controls style and layout, and introduces new features such as animation. 3. JavaScript implements dynamic interaction and enhances functions through DOM operations and asynchronous requests.

Is H5 page production a front-end development? Is H5 page production a front-end development? Apr 05, 2025 pm 11:42 PM

Yes, H5 page production is an important implementation method for front-end development, involving core technologies such as HTML, CSS and JavaScript. Developers build dynamic and powerful H5 pages by cleverly combining these technologies, such as using the &lt;canvas&gt; tag to draw graphics or using JavaScript to control interaction behavior.

How to make pop-up windows with h5 How to make pop-up windows with h5 Apr 06, 2025 pm 12:12 PM

H5 pop-up window creation steps: 1. Determine the triggering method (click, time, exit, scroll); 2. Design content (title, text, action button); 3. Set style (size, color, font, background); 4. Implement code (HTML, CSS, JavaScript); 5. Test and deployment.

See all articles