Details of drag and drop events in HTML5


Browser support

Internet Explorer 9, Firefox, opera 12, chrome and safari 5 support drag and drop.

notes:Drag and drop is not supported in Safari 5.1.2.

HTML5 drag and drop instance

<!DOCTYPE html>
<style type="text/css"> 
#div1 {width:488px;height:70px;padding:10px;border:1px solid #aaaaaa;} 
<script type="text/javascript"> 
function allowDrop(ev) 
function drag(ev) 
function drop(ev) 
var data=ev.dataTransfer.getData("Text");; 
<p>Please drag and drop the image of aseoe logo into the rectangle: P > 0 
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">div> 
<br /> 
<img id="drag1" src="" 
draggable="true" ondragstart="drag(event)" /> 

Set the element to drag and drop

First, to make the element draggable, set the draggable property to true

Drag what – ondragstart and SetData ()

Then, specify what happens when the element is dragged.

In the above example, the ondragstart property calls a function, drag (event), which specifies the data to be dragged.

dataTransfer.setData () method to set the data type and value of the dragged data:

function drag(ev)

In this example, the data type is “text” and the value is the ID of the drag1 element.

Where to put it – ondragover

The ondragover event specifies where to place the dragged data.

By default, data / elements cannot be placed in other elements. If you need to set allow placement, we have to block the default handling of elements.

This is done by calling the event.preventDefault () methods


To place – ondrop

The drop event occurs when the dragged data is placed.

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

function drop(ev)
var data=ev.dataTransfer.getData("Text");;

Code explanation:

Call preventdefault() to avoid the default processing of data by the browser (the default behavior of drop events is to open in the form of links)

Through dataTransfer.getData (“text”) method to get the dragged data. This method will return any data set to the same type in the setdata() method.

The dragged data is the ID (“drag1”) of the dragged element

Append the dragged element to the drop element (target element)


The above is the whole content of this article, I hope the content of this article can help you learn or use HTML5, if you have any questions, you can leave a message to exchange, thank you for your support to developer.

Recommended Today

Use of Android WebView (super detailed usage)

1.1 overview of WebView Android WebView is a special view on the Android platform. It can be used to display web pages. This WebView class can be used to display only one online web page in the app. Of course, it can also be used to develop browsers. The internal implementation of WebView uses WebKit […]