Comment: Call preventDefault() to avoid the browser's default processing of data (the default behavior of drop events is opened in link form) and the dragged data is obtained through the dataTransfer.getData(Text) method. Interested friends can refer to it.
Original effect
Effect after dragging
The code is as follows
[code]
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#div1, #div2
{float:left; width:100px; height:35px; margin:10px;padding:10px;border:1px solid #aaaaa;}
</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>
<img src="/i/w3school_logo_black.gif" draggable="true" ondragstart="drag(event)" />
<div ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<div ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</body>
</html>
[/code]
It may seem a bit complicated, but we can study the different parts of the drag and drop event separately.
Set elements to drag-and-drop
First, to make the element draggable, set the draggable property to true:
<img draggable="true" />
What to drag - ondragstart and setData()
Then, specify what happens when the element is dragged.
In the example above, the ondragstart property calls a function, drag(event), which specifies the data being dragged.
The dataTransfer.setData() method sets 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 draggable element (drag1).
Where to put - ondragover
The ondragover event specifies where to place dragged data.
By default, data/elements cannot be placed in other elements. If you need to set allow placement, we must block the default handling of elements.
This is done by calling the event.preventDefault() method of the ondragover event:
event.preventDefault()
Make placement - ondrop
A drop event occurs when drop data is placed.
In the above example, the ondrop property calls a function, drop(event):
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 drop events is opened in link form) to obtain the dragged data through the dataTransfer.getData(Text) method. This method returns any data set to the same type in the setData() method. The dragged data is the id of the dragged element (drag1) appends the dragged element to the placement element (target element)