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>
<html>
<head>
<style type="text/css">
#div1 {width:488px;height:70px;padding:10px;border:1px solid #aaaaaa;}
</style>
<script type="text/javascript">
function allowDrop(ev)
{
ev.preventDefault();
}
function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<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="https://imgs.developpaper.com/imgs/logo.png"
draggable="true" ondragstart="drag(event)" />
</body>
</html>
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)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
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
event.preventDefault()
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)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}
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)
summary
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.