Talking about the _javascript skills of JS native drag and drop

Source: Internet
Author: User

Can be dragged

Images, links, and text in a Web page can be dragged by default, and HTML5 provides a draggable attribute for all HTML elements, and when the value of this property is true, the element is considered to be dragged.

When you drag an image or link, place the mouse over the image or link, and hold down the mouse to drag it. When you drag text, select the text, and then drag the selected text as you would drag the image.

The dragged element event

Trigger when dragging a picture: Drapstart,drag,dragend event. The target of these three events is the element being dragged.

When you press the mouse button and start moving the mouse, the DragStart event is triggered on the dragged element. When the DragStart event is triggered, the drag event is triggered and the drag event is triggered continuously when the element is dragged, and when the drag stops, the Dragend event is triggered whether the element is placed on a valid drop target or an invalid drop target.

Drop Target Element Events

When an element is dragged onto a valid drop target, it is triggered one time: the Dragenter,dragover,dragleave or Drop event

Whenever an element is dragged onto a drop target, the DragEnter event is triggered, followed by the DragOver event, and the DragOver event is continuously triggered when the dragged element is also moved within the range of the drop target If the element is dragged out of the drop target and the DragOver event is not triggered, the DragLeave event is triggered. If the element is placed in the drop target, the drop event is triggered instead of the DragLeave event. The goals of these events are the elements of the drop target.

Google browser to support the effect of good, Firefox effect is bad

Customizing drop targets

We can turn any element into a valid drop target by overriding the default behavior of the DragEnter and DragOver events

In FF, the default behavior of the drop event is to open the URL that is placed on the drop target. In other words, if you're dragging and dropping the image

To the drop target, the page moves to the image file, and if you drag and drop the text onto the drop target, an invalid URL error is caused.

Therefore, in order for FF to support normal drag-and-drop, the default behavior of the drop event is also canceled to prevent it from opening the URL.

DataTransfer objects

The biggest feature of native drag and drop is the ability to use drag-and-drop events to pass data, so that browsers can natively support drag-and-drop interactivity similar to desktop applications. To use the data transfer function, you need an interface named DataTransfer.

The DataTransfer object is an attribute of the event object, which has two main methods: GetData () and SetData (). SetData () is used to hold values, GetData () is used to get SetData () saved values.

When you drag text in a text box, the browser calls the SetData () method to save the dragged text in the DataTransfer object in "text" format. Similarly, when you drag and drop a link or image, the SetData () method is invoked and the URL is saved. Then, when these elements are dragged onto the drop target, the data can be read through the GetData () method.

The data type saved is "text" or "url", and in HTML5 the two data types are mapped to "Text/plain" and "Text/uri-list"

There is a difference between saving data as text and a URL. If you save the data in text format, the data does not receive any special processing. If you save the data as a URL, the browser treats it as a link in the Web page. In other words, if you put it in another browser window, the browser will open the URL.

Demo:

Text Drag and drop:

<! DOCTYPE html>
 
 

Link drag and drop:

&lt;! DOCTYPE html&gt; &lt;html&gt; &lt;meta charset= "utf-8" &gt; &LT;TITLE&GT;HTML5 link drag and drop &lt;/title&gt; &lt;head&gt; &lt; Style type= "Text/css" &gt; #div1 {width:220px;height:185px;padding:10px;border:1px solid #aaaaaa;} &lt;/style&gt; &lt; /head&gt; &lt;body&gt; &lt;a href= "http://www.baidu.com" id= "AA" &gt; link to Baidu &lt;/a&gt; &lt;div id= "Div1" ondrop= "Drop" ( Event) "Ondragover=" AllowDrop (event) &gt;&lt;/div&gt; &lt;br&gt; &lt;script type= "Text/javascript" &gt;/* ondragover
Events specify where to place the dragged data. By default, data elements cannot be placed into other elements.
 If you need to set up allow placement, we must block the default handling of the element.

*/function AllowDrop (EV) {Ev.preventdefault ();} The function drag (EV) {//datatransfer.setdata () method sets the data type and value of the dragged data the data type is "text" and the value is the text ev.dataTransfer.setData in the P label ("URL"
, document.getElementById (data). href); The function drop (EV) {//Call Preventdefault () to avoid the browser's default handling of the data (the default behavior of the drop event is opened as a link) ev.preventdefault ();/through DataTransfer The. GetData ("Text") method obtains the data that is dragged.
This method returns any data that is set to the same type in the SetData () method.
var data=ev.datatransfer.getdata ("URL");
Ev.target.innerhtml=data; }
&Lt;/script&gt; &lt;/body&gt; &lt;/html&gt; 

Picture drag and drop:

 <! DOCTYPE html>  
 

Drag and drop pictures:

 <! DOCTYPE html>  
 

DropEffect and Effectallowed Properties

With the DataTransfer object, not only is it possible to transmit data, it can also be used to determine what operations the dragged elements and the elements of the drop target can receive. This requires access to its two properties: the DropEffect property and the Effectallowed property.

The DropEffect browser displays different types of cursors based on different values, raising the user's behavior after placement. DropEffect includes the following values:

• "None": cannot put the dragged element here

• "Move": the dragged element should be moved to the drop target

• "Copy": You should copy the dragged element to the drop target

• "link": Indicates that the drop target opens the dragged element (but the dragged element must be a link with a URL)

Browsers will only help you change the type of cursor, but what you want to achieve is to be implemented by the developer yourself.

The DropEffect property is only useful with the effectallowed attribute, which represents the dropeffect behavior that allows the element to be dragged, and its value has the following types:

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

• ' None ': The dragged element cannot have any behavior

• "Copy": Only allow placement behavior with a value of "copy"

• "link": Only allow placement behavior with a value of "link"

• ' Move ': Allow only placement behavior with values of ' move '

• "Copylink": Allow placement behavior with values of "copy" and "link"

• "Copymove": Allow placement behavior with values of "copy" and "Move"

• "Linkmove": Allow placement behavior with values of "link" and "Move"

• "All": Allow all placement behavior

The Effectallowed property must be set in the Ondragstart event handler

Demo

&lt;! DOCTYPE html&gt; &lt;html lang= "en" &gt; &lt;head&gt; &lt;meta charset= "UTF-8" &gt; &lt;title&gt;my-dropeffect and EFFEC tallowed&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;a href= "http://www.baidu.com" &gt; Link to Baidu &lt;/a&gt; &lt;div style = "width:200px; height:100px; Float:right; Background:red "id=" DropTarget "&gt;&lt;/div&gt; &lt;div id=" Output "&gt;&lt;/div&gt; &lt;script type=" text/ JavaScript "src=" Eventutil.js "&gt;&lt;/script&gt; &lt;script type=" Text/javascript "&gt; var droptarget = document.get
  Elementbyid ("DropTarget");//Get drop target var link = document.links[0]; Console.log (document.links);//htmlcollection[a]//console.log (document.links[0));//&lt;a href= "http:// Www.baidu.com "&gt; Function handleevent (event) {document.getElementById (" Output "). InnerHTML + = Event.type +"
      ;br&gt; "; Switch (event.type) {case ' DragStart ': Case "dragend": Event.dataTransfer.dropEffect = "link";//Table The drop target opens the dragged element. To use DropEffect, you must set the appropriateThis is set to link break;
          Case "DragEnter": The Case "DragOver": Eventutil.preventdefault (event);
        event.dataTransfer.effectAllowed = "link";//= value allows "link" dropeffect break; Case "Drop": Case "DragLeave": droptarget.innerhtml = event.dataTransfer.getData ("url") | |
        Event.dataTransfer.getData ("Text/uri-list"); Event.dataTransfer.getData ("url") | | Event.dataTransfer.getData ("Text/uri-list"); is read URL}} eventutil.addhandler (DropTarget, "DragEnter", Handl
    Eevent);
    Eventutil.addhandler (DropTarget, "DragOver", handleevent);
    Eventutil.addhandler (DropTarget, "DragLeave", handleevent);
    Eventutil.addhandler (DropTarget, "drop", handleevent);
    Eventutil.addhandler (link, "DragStart", handleevent);
  Eventutil.addhandler (link, "Dragend", handleevent);
 &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;

Demo2:

&lt;! DOCTYPE html&gt; &lt;html lang= "en" &gt; &lt;head&gt; &lt;meta charset= "UTF-8" &gt; &lt;title&gt;my-dropeffect and EFFEC tallowed&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;a href= "http://www.baidu.com" &gt; Link to Baidu &lt;/a&gt; &lt;p&gt; haha &lt;/p&gt; &lt;div style= "width:200px; height:100px; Float:right; Background:red "id=" DropTarget "&gt;&lt;/div&gt; &lt;div id=" Output "&gt;&lt;/div&gt; &lt;script type=" text/ JavaScript "src=". /eventutil.js "&gt;&lt;/script&gt; &lt;script type=" Text/javascript "&gt; var droptarget = document.getElementById ("
  DropTarget ");//Get drop target var link = document.links[0]; Console.log (document.links);//htmlcollection[a]//console.log (document.links[0));//&lt;a href= "http:// Www.baidu.com "&gt; Function handleevent (event) {document.getElementById (" Output "). InnerHTML + = Event.type +"
      ;br&gt; "; Switch (event.type) {case ' DragStart ': Case ' dragend ': event.dataTransfer.dropEffect = ' move ';//table Example should move the dragged element to thePlace the target case "DragEnter": The Case "DragOver": Eventutil.preventdefault (event);
        event.dataTransfer.effectAllowed = "move";//= value allows the dropeffect break of "move";
          Case "Drop": Case "DragLeave": Eventutil.preventdefault (event);
      This is to prevent the default behavior of the drop event: Open the URL droptarget.innerhtml = Event.dataTransfer.getData ("Text") that is placed on the drop target;
    } eventutil.addhandler (DropTarget, "DragEnter", handleevent);
    Eventutil.addhandler (DropTarget, "DragOver", handleevent);
    Eventutil.addhandler (DropTarget, "DragLeave", handleevent);
    Eventutil.addhandler (DropTarget, "drop", handleevent);
    Eventutil.addhandler (link, "DragStart", handleevent);
  Eventutil.addhandler (link, "Dragend", handleevent);
 &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;

Above this article about the original drag and drop JS is a small set to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.