Drag and drop
Drag and drop is a common feature where you grab an object and then drag it to another location.
In HTML5, drag and drop is part of the standard, and any element can be dragged and dropped.
Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support dragging.
Note:Safari 5.1.2 does not support dragging.
Example:
First, in order to make the element draggable, set thedraggable attributeto true:
Then, specify that when the element is dragged, what will happen What.
In the above example,ondragstart attributecalls a function, drag(event), which specifies the data to be dragged.
dataTransfer.setData() methodSet the data type and value of the dragged data:
function drag(ev) { ev.dataTransfer.setData("Text",ev.target.id); }
In this example, data The type is "Text" and the value is the id of the draggable element ("drag1").
ondragover eventSpecifies where to place the dragged data.
By default, data/elements cannot be placed into other elements. If we need to allow placement, we must prevent the default handling of the element.
This is done by calling theevent.preventDefault() method ofondragover event: event.preventDefault()
When the dragged data is placed, a drop will occur event.
In the above example, the ondrop attribute calls a function,drop(event):
function drop(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); }
Code explanation:
CallpreventDefault()to avoid the browser's default processing of data (the default behavior of the drop event is to open it as a link)
ThroughdataTransfer.getData("Text" ) MethodGet the dragged data. 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)
Drag back and forth:
If you want to drag back and forth between two places, just slightly modify the above code.
Change the code in the body to:
Then add #p2 to the style:
This way you can drag and drop back and forth.
The above is the content of the implementation code of HTML5 drag and drop effect. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!