HTML5 drag-and-drop implementation example and html5 drag-and-drop example
HTML5 is now a new technical term in front-end circles. Many companies also regard HTML5 as a hard skill requirement, however, I'm afraid many front-ends do not know how to implement HTML5 drag-and-drop.
After reading the video from geek college, I learned about the idea. So sort out the backups for future reference. Example 1:
Index.html
1 <!doctype html> 2
App1.js
1 /** 2 * app1.js 3 */ 4 5 var oBox1, 6 oBox2, 7 oImg1; 8 9 window.onload = function(){10 oBox1 = document.getElementById('box1');11 oBox2 = document.getElementById('box2');12 oImg1 = document.getElementById('img1');13 14 //15 oBox1.ondragover = oBox2.ondragover = function(e){16 e.preventDefault();17 };18 19 //20 oImg1.ondragstart = function(e){21 e.dataTransfer.setData('text', e.target.id);22 };23 24 oBox1.ondrop = dropImg;25 oBox2.ondrop = dropImg;26 };27 28 function dropImg(e){29 e.preventDefault();30 var tempImg = document.getElementById(e.dataTransfer.getData('text'));31 e.target.appendChild(tempImg);32 }
Knowledge points involved
The following events are triggered during drag-and-drop:
Trigger an event (Source Element) on the drag target)
Ondragstart-triggered when the user starts to drag an element
Ondrag-triggered when the element is being dragged
Ondragend-triggered after the user completes element dragging
Events triggered when the target is released
Ondragenter-this event is triggered when an object dragged by the mouse enters its container range.
Ondragover-this event is triggered when a dragged object is dragged within the range of another object container
Ondragleave-this event is triggered when an object dragged by the mouse leaves its container range.
Ondrop-this event is triggered when the mouse key is released during a drag process.
Event object (replaced by "e)
E.tar get
The description on W3Cschool is: the elements that trigger this event (the target node of the event) are returned. This target attribute is only compatible with ie9 and later versions.
E. preventDefault ()
Cancels the default action of an event.
E. dataTransfer. setData ()
Set the data type and value of the dragged data.
E. dataTransfer. setData ("Text", ev.tar get. id); // The first parameter is Text (lowercase)
E. dataTransfer. getData ()
Obtain the dragged data.
e.dataTransfer.getData("Text");