Home >Web Front-end >H5 Tutorial >Html5 implements how to drag and drop images between two div elements_html5 tutorial tips
Original effect
The effect after dragging
The code is as follows
Set element as draggable
First, in order to make the element draggable, set the draggable attribute to true:
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:
- 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:
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):
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)