Case analysis of HTML5 native drag and drop

Source: Internet
Author: User

Original link: http://www.cnblogs.com/zhenwen/p/5855107.html

HTML5 provides native drag-and-drop JavaScript APIs that are easy to use.

Compatibility:

For PC-side browsers, Firefox, Chrome, Safari support is good, and IE and Edge browser Some features are not supported, such as IE10 and IE11, Edge for Datatransfer.setdata (format,data), only defined " Text "and" URL "are two valid data types. The HTML5 specification allows various MIME types to be supported.

Detailed reference here: http://caniuse.com/#search =drag

This paper implements HTML5 native drag-and-drop application demo, using the usual methods and properties, compatible with modern browsers, or first look at the effect:

Detailed introduction below--

Native drag-and-drop events:

Events applied to the dragged element:

    • DragStart

Pressing the mouse and starting to move the mouse will trigger the DragStart event on the dragged element.

Note: To use the native drag-and-drop feature of HTML5 to make the element draggable, you need to set the Draggable property. By default, images, links, and selected text are draggable because their Draggable property is automatically set to true.

    

    • Drag

When the DragStart event is triggered, the drag event is triggered, and the event continues to be triggered while the element is being dragged.

    • Dragend

The Dragend event is triggered when the drag stops (releasing the mouse).

Events applied to the drop target:

    • DragEnter

The DragEnter event is triggered whenever an element is dragged onto the drop target.

    • DragOver

When the DragEnter event is triggered, the DragOver event is triggered and continues to trigger as long as the dragged element moves within the range of the drop target.

    • DragLeave

Element is dragged out of the drop target, the DragOver event no longer occurs, but the DragLeave event is triggered.

    • Drop

element is placed in the drop target, the drop event is triggered instead of the DragLeave event.

  Note: (1) the dragged element and drop target can be set to the same element, and the drop event can also be triggered on itself, although it seems to be useless. =

     (2) the reference standard where the dragged element enters the drop target range and departs is the position of the mouse, not the boundary of the image dragged below the mouse

(3) the image displayed at the bottom of the mouse cursor when dragging, the default is a copy of the element, in the DragStart event to complete the copy of the element (also can be customized by setdragimage () the mouse drag elements), so to hide the original element, Preferably handled in the drag event, which is processed after copying (see source code at the end of the article)

DataTransfer Object

The DataTransfer object is a property of the event object and can only be accessed in the event handler for the drag-and-drop event. Also, some methods and properties of the DataTransfer object can only be set in a specific drag-and-drop event.

  Common methods:

    • SetData (Format,data)

In the DragStart event, call the SetData () function for the dragged element, set the data to be passed, and use the data to pass the string format from the dragged element to the drop target.

The first parameter is the data type, where IE only defines two valid data types: text and URL, and the second argument is a string that represents the data to be passed.

    • GetData (format)

In the drop event, call the GetData () function for the drop target to get the data passed.

The first parameter is the data type set in SetData ()

    • Setdragimage (element, x, y)

Specifies a pair of images that appear below the cursor when the drag occurs. Accepts 3 parameters: the HTML element to display and the x, y coordinates of the cursor in the image. Where the HTML element can be an image, or it can be another element.

This property is not supported by IE10, IE11, Edge browser.

    • ClearData (format)

Clears the data saved in a specific format.

  Common Properties:

    • DropEffect

In the DragEnter event handler, set the value of the DropEffect property for the drop target, determining which placement behavior the dragged element can perform (while dragging the element onto the drop target, a different cursor symbol is displayed)

None: The dragged element cannot be placed here. This is the default value for all elements except the text box.

Move: The dragged element should be moved to the drop target.

Copy: The dragged element should be copied to the drop target.

Link: The drop target opens the dragged element (but the dragged element must be a link with a URL address).

  

    • Effectallowed

In the DragStart event handler, the value of the Effectallowed property is set for the dragged element, indicating which dropeffect of the element is allowed to be dragged and used with the DropEffect attribute above.

Uninitialized: No placement behavior is set for the dragged element.

None: The dragged element cannot have any behavior.

Copy: Only dropeffect with a value of "copy" is allowed.

Link: only dropeffect with a value of "link" is allowed.

Move: Only dropeffect with a value of "move" is allowed.

Copylink: Allows dropeffect with a value of "copy" and "link".

Copymove: Allows dropeffect with a value of "copy" and "Move".

Linkmove: Allows dropeffect with a value of "link" and "move".

All: Allow any dropeffect.

For some other methods and properties of DataTransfer, and a more detailed introduction, see here Https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API

The source part of the end of text--

HTML code:

<div id= ' container ' >
<div id= ' wrap ' >



</div>
<div id= ' cart ' ></div>
</div>

CSS code:

*{
margin:0;
padding:0;
}
body{
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
User-select:none;
}
#wrap {
height:100px;
Text-align:center;
}
img{
width:100px;
height:100px;
cursor:-webkit-grab;
cursor:-moz-grab;
Cursor:grab;
}
#cart {
width:500px;
height:100px;
border-radius:20px;
margin:50px Auto 0;
Background-color:orange;
}
#cart. hover{
background-color:red;
}
#cart img{
width:70px;
height:70px;
margin:15px;
}


*{    margin:0;    padding:0;} body{    -webkit-user-select:none;        -moz-user-select:none;        -ms-user-select:none;        User-select:none;} #wrap {    height:100px;    Text-align:center;} img{    width:100px;    height:100px;    cursor:-webkit-grab;    cursor:-moz-grab;    Cursor:grab;} #cart {    width:500px;    height:100px;    border-radius:20px;    margin:50px Auto 0;    Background-color:orange;} #cart. hover{    background-color:red;} #cart img{    width:70px;    height:70px;    margin:15px;}

JS Code:

//Three events of the dragged element
function DragStart (e) {
E = eventutil.getevent (e);
var target = Eventutil.gettarget (e);
E.datatransfer.setdata ("text", target.title);
//Because IE10, IE11, and Edge do not support the Setdragimage () method, you need to determine
if (e.datatransfer.setdragimage) {
E.datatransfer.setdragimage (target,50,50);
}

//effectallowed event and DropEffect event with
e.datatransfer.effectallowed = ' move ';
Dragelement = target;
}
Function Drag (e) {
E = eventutil.getevent (e);
var target = Eventutil.gettarget (e);
SetOpacity ( target,0);
}
Function Dragend (e) {
E = eventutil.getevent (e);
var target = Eventutil.gettarget (e);
SetOpacity ( target,1);
}

//Drop target four events
function DragEnter (e) {
E = eventutil.getevent (e);
var target = Eventutil.gettarget (e);
// Important! Overrides the default behavior of the DragEnter event so that it can trigger the drop event
Eventutil.preventdefault (e);
//dropeffect Events and effectallowed events with
E.datatransfer.dropeffect = ' move ';
Target.classname = ' hover ';
}
Function DragOver (e) {
E = eventutil.getevent (e);
//important! Overrides the default behavior of the DragOver event so that it can trigger the drop event
Eventutil.preventdefault (e);
}
Function DragLeave (e) {
E = eventutil.getevent (e);
var target = Eventutil.gettarget (e);
Target.classname = ";
}
Function Drop (e) {
E = eventutil.getevent (e);
var target = Eventutil.gettarget (e);
var title = E.datat Ransfer.getdata ("text");
Console.warn (' Add%s to cart! ', title);
Target.classname = ";
DragElement.parentNode.removeChild (dragelement);
var img = Dragelement.clonenode ();
Img.draggable = false;
SetOpacity (img,1);
Cart.appendchild (IMG);

//Important! To allow Firefox to support normal drag-and-drop, cancel the default behavior of the drop event
Eventutil.preventdefault (e);
}


//Set Transparency
function setopacity (element,value) {
if (typeof element.style.opacity!= ' undefined ') {
Element.style.opacity=value;
}else{
Element.style.filter = "Alpha (opacity=" +value*100+ ")";
}
}
//event handling, doing compatibility
Var eventutil={
//Add event handler
Addhandler:function (element,type,handler) {
If (Element.addeventlistener) {
Element.addeventlistener (type,handler,false);
}else if (element.attachevent) {
Element.attachevent ("on" +type,handler);
}else{
element["on" +type]=handler;
}
},
//Get Event Object
Getevent:function (event) {
return event?event:window.event;
},
//Gets the destination of the event
Gettarget:function (event) {
Return event.target| | Event.srcelement;
},
//cancels the default event
Preventdefault:function (event) {
if (event.preventdefault) {
Event.preventdefault (); br>}else{
Event.returnvalue=false;
}
}
};

var IMGs = document.getelementsbytagname ("img"),
Cart = document.getElementById (' cart '),
Dragelement = null;

for (var i=0; iEventutil.addhandler (Imgs[i], ' DragStart ', dragstart);
Eventutil.addhandler (Imgs[i], ' drag ', drag);
Eventutil.addhandler (Imgs[i], ' dragend ', dragend);
}
Eventutil.addhandler (cart, ' dragenter ', dragenter);
Eventutil.addhandler (cart, ' dragover ', dragover);
Eventutil.addhandler (cart, ' dragleave ', dragleave);
Eventutil.addhandler (Cart, ' drop ', drop);


The three event function of the dragged element DragStart (e) {e = Eventutil.getevent (e);  var target = Eventutil.gettarget (e);  E.datatransfer.setdata ("text", target.title); Because IE10, IE11, and Edge do not support the Setdragimage () method, you need to determine if (e.datatransfer.setdragimage) {e.datatransfer.setdragimage (target,   50,50);  } The//effectallowed event and the DropEffect event are paired with e.datatransfer.effectallowed = ' move '; Dragelement = target;}  function Drag (e) {e = Eventutil.getevent (e);  var target = Eventutil.gettarget (e); SetOpacity (target,0);}  function Dragend (e) {e = Eventutil.getevent (e);  var target = Eventutil.gettarget (e); SetOpacity (target,1);}  Drop target four event function DragEnter (e) {e = Eventutil.getevent (e);  var target = Eventutil.gettarget (e); Important!   Overrides the default behavior of the DragEnter event so that it can trigger a drop event Eventutil.preventdefault (e);  DropEffect events and effectallowed events with e.datatransfer.dropeffect = ' move '; Target.classname = ' hover ';}  function DragOver (e) {e = Eventutil.getevent (e); Important! Overrides the default behavior of the DragOver event so that it can trigger a drop event Eventutil.preventdefault (e); }function DragLeave(e)  {e = Eventutil.getevent (e);  var target = Eventutil.gettarget (e); Target.classname = ";}  function Drop (e) {e = Eventutil.getevent (e);  var target = Eventutil.gettarget (e);  var title = E.datatransfer.getdata ("text"); Console.warn (' Add%s to cart!  ', title);  Target.classname = ";  DragElement.parentNode.removeChild (dragelement);  var img = Dragelement.clonenode ();  Img.draggable = false;  SetOpacity (img,1);  Cart.appendchild (IMG); Important! To allow Firefox to support normal drag-and-drop, cancel the default behavior of the drop event Eventutil.preventdefault (e); }//Set Transparency function setopacity (element,value) {if (typeof element.style.opacity!= ' undefined ') {element.style.opacity=  Value          }else{element.style.filter = "Alpha (opacity=" +value*100+ ")"; }}//event handling, do compatible with VAR eventutil={//Add Event handler addhandler:function (Element,type,handler) {if (element.addeventliste        NER) {Element.addeventlistener (type,handler,false);          }else if (element.attachevent) {element.attachevent ("on" +type,handler); }else{element["on" +type]=handler;     }},//Gets the event object Getevent:function (event) {return event?event:window.event; },//Get Event Target Gettarget:function (event) {return event.target| |     Event.srcelement; },//Cancel default event Preventdefault:function (event) {if (Event.preventdefault) {Event.preventdefault ()           ;          }else{Event.returnvalue=false; }}};var IMGs = document.getElementsByTagName ("img"), cart = document.getElementById (' cart '), dragelement = null  ; for (var i=0; i

Reference: JavaScript advanced Programming, MDN

Case analysis of HTML5 native drag and drop

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.