HTML 5 Drag and drop (Drag and drop), dragdrop
Browser support
Internet Explorer 9, Firefox, Opera 12, Chrome, and Safari 5.
1. Set the label draggable attribute to true.
2. added the ondragstart attribute to the tag and called a function drag (Event).
Function drag (ev ){
Ev. dataTransfer. setData ("Text", ev.tar get. id);} // you can specify the data type and value of the dragged data.
3. Add the ondragover attribute to the location (target element) tag to call a function allowDrop (event ).
Function allowDrop (ev ){
Ev. preventDefault ();} // prevents the browser from processing data by default.
4. Add the ondrop attribute to the location (target element) label to be dragged and dropped to call a function drop (event ).
A drop event occurs when data is dragged.
Function drop (ev ){
Ev. preventDefault (); // prevents the browser from processing data by default.
Var data = ev. dataTransfer. getData ("Text"); // obtain the dragged data. This method returns any data set to the same type in the setData () method.
Ev.tar get. appendChild (document. getElementById (data);} // append the dragged element to the target element.
5. Example:
<Script type = "text/javascript">
Function allowDrop (ev ){
Ev. preventDefault ();}
Function drag (ev ){
Ev. dataTransfer. setData ("Text", ev.tar get. id );}
Function drop (ev ){
Ev. preventDefault ();
Var data = ev. dataTransfer. getData ("Text ");
Ev.tar get. appendChild (document. getElementById (data ));}
</Script>
<Div id = "div1" ondrop = "drop (event)" ondragover = "allowDrop (event)">
</Div>
<Div id = "div2" ondrop = "drop (event)" ondragover = "allowDrop (event)"> </div>
Run the following command:
We can drag and drop images back and forth in div1 and div2.