HTML5 drag and drop
Drag and drop is a common feature that drags an object and drags it to another location.
In HTML5, drag and drop is part of the standard, and any element can be dragged and dropped.
Drag and drop (Drag and drop) is part of the HTML5 standard.
Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support dragging.
Note: Safari 5.1.2 does not support dragging.
HTML5 drag and drop instance
The following example is a simple drag and drop instance:
Run the program and try to drag the picture
The program may seem a bit complicated, but we can study different parts of the drag and drop event separately.
Set elements to be draggable
First, to make the element draggable, set the draggable property to true :
Drag what - ondragstart and setData()
Then, what happens when the element is dragged.
In the above example, the ondragstart property calls a function, drag, which specifies the data being dragged.
The dataTransfer.setData() method sets the data type and value of the data being dragged:
In this example, the data type is "Text" and the value is the id of the draggable element ("drag1").
Where to put it - ondragover
The ondragover event specifies where to place the dragged data.
By default, data/elements cannot be placed into other elements. If we need to set the allowed placement, we must prevent the default handling of the elements.
This is done by calling the event.preventDefault() method of the ondragover event:
Place - ondrop
The drop event occurs when the dragged data is placed.
In the above example, the ondrop property calls a function, drop(event):
Call preventDefault() to prevent the browser from processing the default data (the default behavior of the drop event is to open as a link)
The dragged data is obtained by the dataTransfer.getData("Text") method. This method will return any data of the same type set in the setData() method.
The dragged data is the id of the dragged element ("drag1")
Append the dragged element to the drop element (the target element)
How to drag and drop an image between two <div> elements.
Try running the program