In the HTML5 to implement drag-and-drop operation, relative to the previous implementation through the mouse operation, it is much simpler, data security is more secure. It takes only a few steps to do this.
- Adds an attribute to the dragged element
draggable
, if it is a file drag and drop.
- Initializes the relevant data information in the dragged element
dragstart
, primarily the DataTransfer
object.
- In the event of the target element
dragover
, its default action is canceled.
- In the event of the target element, the data that is
drop
received is processed.
- In the event of being dragged elements
dragend
, do the aftercare work. If not, you can omit it.
The approximate code is as follows:
<div id="Source"draggable="draggable">source</div><div id="Target">target</div><script type="Text/javascript">vartarget = document.getElementById ('Target');varSource = document.getElementById ('Source'); Source.ondragstart=function (e) {e.datatransfer.effectallowed='Copymove'; E.datatransfer.setdata ('Test','TestData');}; Target.ondragover=function (e) {E.datatransfer.dropeffect='Move'; E.preventdefault (); //not less};target.ondrop=function (e) {varElem = Document.createelement ('a'); Elem.innerhtml= E.datatransfer.getdata ('Test'); E.target.appendchild (elem);};</script>
Draggable Property
Draggable is an enumeration property that specifies whether a label can be dragged or not. The following four types of values are available:
true
: Indicates that this element can be dragged.
false
: Indicates that this element is not draggable.
auto
: img
the label label href
can be dragged and removed, and the a
other labels indicate that they cannot be dragged.
- Any other value: Indicates not to be dragged.
What to drag-ondragstart and SetData ()
The Ondragstart property invokes a function, drag (event), which specifies the data being dragged.
The Datatransfer.setdata () method sets the data type and value of the dragged data.
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 must block the default handling of elements.
This is done by calling the event . Preventdefault () method of the OnDragOver events.
HTML 5 for drag-and-drop effects