Home > Web Front-end > H5 Tutorial > body text

Html5 implements how to drag and drop images between two div elements_html5 tutorial tips

WBOY
Release: 2016-05-16 15:49:51
Original
1769 people have browsed it

Original effect

The effect after dragging

The code is as follows


Copy code
The code is as follows:

[code]











< ;/body>


[/code]
It may look a bit complicated, but we can study the different parts of the drag and drop event separately.

Set element as draggable

First, in order to make the element draggable, set the draggable attribute to true:

Copy the code
The code is as follows :


What to drag - 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 the data type and value of the dragged data:

Copy code
The code is as follows :

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 draggable element ("drag1"). Where to put

- ondragover

The ondragover event specifies where to place the dragged data.

By default, data/elements cannot be placed inside 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:

Copy code
The code is as follows:

event.preventDefault()

to place - ondrop

When the dragged data is dropped, the drop event will occur.

In the above example, the ondrop attribute calls a function, drop(event):

Copy code
The code is as follows:

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) and obtain 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 placed element (target element)

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!