How does HTML5 implement drag-and-drop of elements?
I am afraid many front-end users do not know how to implement HTML5 drag-and-drop operations. This article describes how to implement HTML5 drag-and-drop operations. Sort the backups for future reference.
Example 1:
Index.html
Copy XML/HTML Code to clipboard
- <! Doctype html>
- <Html>
- <Head>
- <Meta charset = "UTF-8">
- <Title> Drag </title>
- <Style>
- . Box {
- Width: 400px;
- Height: 400px;
- Float: left;
- }
- # Box1 {
- Background: # CCC;
- }
- # Box2 {
- Background: # FF0;
- }
- </Style>
- </Head>
- <Body>
- <Div id = "box1" class = "box"> </div>
- <Div id = "box2" class = "box"> </div>
Copy the content to the clipboard using JavaScript Code
- <Script src = "app1.js"> </script>
- </Body>
- </Html>
- App1.js
- /**
- * App1.js
- */
- Var oBox1,
- OBox2,
- OImg1;
- Window. onload = function (){
- OBox1 = document. getElementById ('box1 ');
- OBox2 = document. getElementById ('box2 ');
- OImg1 = document. getElementById ('img1 ');
- //
- OBox1.ondragover = oBox2.ondragover = function (e ){
- E. preventDefault ();
- };
- //
- OImg1.ondragstart = function (e ){
- E. dataTransfer. setData ('text', e.tar get. id );
- };
- OBox1.ondrop = dropImg;
- OBox2.ondrop = dropImg;
- };
- Function dropImg (e ){
- E. preventDefault ();
- Var tempImg = document. getElementById (e. dataTransfer. getData ('text '));
- E.tar get. appendChild (tempImg );
- }
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:
The Code is as follows: e. dataTransfer. setData ("Text", ev.tar get. id); // The first parameter is Text (lowercase)
E. dataTransfer. getData ()
Get dragged data:
The Code is as follows: e. dataTransfer. getData ("Text ");
The above is all the content of this article, hoping to help you learn.
Original article: http://www.cnblogs.com/oovwall/p/5213580.html