A talk on the deep understanding of JavaScript native drag-and-drop _javascript skills

Source: Internet
Author: User
Tags setinterval string format

Front.

Drag and Drop (DRAG-AND-DROP,DND) is actually two actions--drag and drop. So, it involves two elements. One is the dragged element, called the drag-and-drop source, and the other is the target to be placed, called the drag-and-drop target. This article will introduce the native drag-and-drop in detail by splitting the two concepts

Drag and drop source

What kind of element is the drag-and-drop source?

HTML5 sets a draggable attribute for all HTML elements, indicating whether the element can be dragged

The image and linked draggable properties are automatically set to True, and the default value for other elements is false

[note] You must set draggable= ' true ' to take effect, setting only draggable does not work

By default, text cannot be dragged until it is selected, and images and links can be dragged at any time. Other elements cannot be dragged and dropped

<input value= "Text drag" >

<a href= "#" > Links can be dragged </a>
<div id= "test" style= "Height:30px;width:300px;background:pink;" > element cannot be dragged </div>

When you set the Draggable property for an element, the normal element can also be dragged

<div draggable= "true" style= "Height:30px;width:100px;background:pink;" ></div>

Compatible

The Ie9-browser does not support the Draggable property, but the DragDrop () method can be invoked by the MouseDown event handler to implement the drag effect

<div id= "test" style= "Height:30px;width:300px;background:pink;" ></div> 
<script>
test.onmousedown = function () {
this.dragdrop ();
}
</script>

[note] If Firefox supports the Draggable property, you must add a Ondragstart event handler and use the SetData () method to start the effect on the DataTransfer object

Drag-and-drop events

Drag-and-drop sources involve 3 drag-and-drop events. When you drag a drag-and-drop source, the 3 events of DragStart, drag, and dragend are triggered sequentially

DragStart

When you press the mouse button and start moving the mouse, the DragStart event is triggered on the dragged element. At this point the cursor becomes a "cannot put" symbol (there is a backslash in the circle), which means you can't put the element on top of yourself.

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 (whether the element is placed in a valid drop target or on an invalid drop target)

<div id= "Test" draggable= "true" style= "Height:30px;width:100px;background:pink;" >0</div> 
<script>
var timer,i=0;
Test.ondragstart = function () {
this.style.backgroundColor = ' lightgreen ';
}
Test.ondrag = function () {
if (timer) return;
Timer = setinterval (function () {
test.innerhtml = i++;
},100)
}
test.ondragend = function () {
clearinterval (timer);
Timer = 0;
This.style.backgroundColor = ' pink ';
}
</script>

Drag and Drop target

Drag-and-drop targets are targets that are placed when the dragged element releases the mouse

When a drag-and-drop source is dragged onto a drop target, the four events DragEnter, DragOver, and dragleave or drop are triggered sequentially

DragEnter

Triggers the DragEnter event whenever an element is dragged onto a drop target

DragOver

The DragOver event continues to be triggered when the dragged element moves within the range of the drop target

DragLeave

Triggers the DragLeave event if the element is dragged out of the drop target

Drop

Triggers the drop event if the element is placed in the drop target

[Note that the default behavior of the]firefox browser's drop event is to open the URL that is placed on the drop target.) To enable Firefox to support normal drag-and-drop, also remove the default behavior of the drop event

By default, the target element is not allowed to be placed, so the drop event does not occur. As long as the default behavior is blocked in the DragOver and DragEnter events, the drop event can be allowed to become the allowed drop target. At this point, the cursor becomes a symbol that allows placement

<div id= "Test" draggable= "true" style= "height:30px;width:130px;background:pink;float:left;" > Drag and drop source </div> <div id= "target" style= "float:right;height:200px;width:200px;background:lightblue;"
> Drag and drop target </div> <script> var timer,i=0;
var timer1,i1=0; Compatible ie8-Browser Test.onmousedown = function () {if (This.dragdrop) {This.dragdrop ();}} Test.ondragstart = function () {This.st
Yle.backgroundcolor = ' LightGreen ';
this.innerhtml = ' Start dragging '; } Test.ondrag = function () {if (timer) return; timer = setinterval (function () {test.innerhtml = ' element has been dragged ' + ++i + ' seconds ';},100
0);  } test.ondragend = function () {clearinterval (timer); timer = 0;i =0; this.innerhtml = ' End drag '; This.style.backgroundColor =
' Pink '; } Target.ondragenter = function (e) {e = e | | | event; if (E.preventdefault) {E.preventdefault ();}
else{e.returnvalue = false;} this.innerhtml = ' element into target area ';
This.style.background = ' red '; } target.ondragover = function (e) {e = e | | | event; if (E.preventdefault) {E.preventdefault ();} else{E.REturnvalue = false;
} if (timer1) return;
Timer1 = setinterval (function () {target.innerhtml = ' element has entered ' + (++I1) + ' seconds ';},1000); } Target.ondragleave = function () {clearinterval (timer1); timer1 = 0;i1=0; this.innerhtml = ' element has left target area '; this.style.backg
Roundcolor = ' lightblue '; } Target.ondrop = function () {clearinterval (timer1); timer1 = 0;i1=0; this.innerhtml = ' element has landed in target area '; this.style.background 
Color = ' orange '; } </script>

DataTransfer objects

In order to implement data interchange in a drag-and-drop operation, the DataTransfer object is introduced, which is an attribute of the event object that is used to pass data in string format from the dragged element to the drop target

There are two main methods for DataTransfer objects: GetData () and SetData ()

GetData () can get the value saved by SetData (). The first parameter of the SetData () method, and the only parameter to the GetData () method, is a string that represents the saved data type, with a value of "text" or "URL"

IE defines only two valid data types for "text" and "URL", while HTML5 expands this to allow for the designation of various MIME types. For backward compatibility, HTML5 also supports "text" and "URLs", but these two types are mapped to "Text/plain" and "Text/uri-list"

In fact, the DataTransfer object can hold a value for each MIME type. In other words, there's nothing wrong with saving a piece of text and a URL in this object at the same time

[note] data stored in the DataTransfer object can only be read in the drop event handler

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 GetData ()

 <div> please pick some of the text that is different from this heap of content move to drop target </div> <div id= "target" style= Margin-top:20px;height:100px;width:200px;background:lightblue; " 
> Drop target </div> <div id= "result" ></div> <script> target.ondragenter = function (e) {e = e | | event; if (E.preventdefault) {E.preventdefault ();}
else{e.returnvalue = false;} this.innerhtml = ' element into target area ';
This.style.background = ' red '; } target.ondragover = function (e) {e = e | | | event; if (E.preventdefault) {E.preventdefault ();}
else{e.returnvalue = false;}} 
Target.ondragleave = function (e) {e = e | | event;
this.innerhtml = ' element has left the target area ';
This.style.backgroundColor = ' lightblue '; } Target.ondrop = function (e) {e = e | | | event; if (E.preventdefault) {E.preventdefault ();}
else{e.returnvalue = false;} result.innerhtml = ' The text that falls into the target area is: ' + e.datatransfer.getdata (' text ');
this.innerhtml = ' element has landed in the target area '; 
This.style.backgroundColor = ' orange '; } </script> 

Of course, you can also call SetData () in the DragStart event handler to manually save the data you want to transfer for future use

<div id= "Test" draggable= "true" data-value= "This is a secret" style= "Height:30px;width:100px;background:pink;" > Drag source </div> <div id= "target" style= "margin-top:20px;height:100px;width:200px;background:lightblue;" > Drop target </div> <div id= "result" ></div> <script>//compatible ie8-Browser Test.onmousedown = function () {if (
This.dragdrop) {This.dragdrop ();}} Test.ondragstart = function (e) {e = e | | | event; e.datatransfer.setdata (' Text ', Test.getattribute (' Data-value ')); target . OnDragEnter = function (e) {e = e | | | event; if (E.preventdefault) {E.preventdefault ();}
else{e.returnvalue = false;} this.innerhtml = ' element into target area ';
This.style.background = ' red '; } target.ondragover = function (e) {e = e | | | event; if (E.preventdefault) {E.preventdefault ();}
else{e.returnvalue = false;}} 
Target.ondragleave = function (e) {e = e | | event;
this.innerhtml = ' element has left the target area ';
This.style.backgroundColor = ' lightblue '; } Target.ondrop = function (e) {e = e | | | event; if (E.preventdefault) {e.preventdeFault ();
}else{e.returnvalue = false;} result.innerhtml = ' The text that falls into the target area is: ' + e.datatransfer.getdata (' text ');
this.innerhtml = ' element has landed in the target area '; 
This.style.backgroundColor = ' orange '; } </script>

Change the cursor

With the DataTransfer object, not only can the data be transmitted, but it can also be used to determine what actions can be taken by the dragged element and the element that is the target of the 罝. To do this, you need access to the two properties of the DataTransfer object: DropEffect and effectallowed

In fact, these two properties are of little use, except that the drag source changes a different cursor when it moves on the drag target (except in one case)

DropEffect

The DropEffect property can know which placement behavior the dragged element can perform. This property has the following 4 possible values

' None ': You cannot put the dragged element here. This is the default value for all elements except the text box (at which point the drop event will not be triggered)

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

"Copy": The dragged element should be copied 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)

When you drag an element onto a drop target, each of these values causes the cursor to be displayed as a different symbol

[note] The DropEffect property must be set for the drop target in the OnDragOver event handler

Effectallowed

The DropEffect property is only useful if it is paired with the Effectallowed property. The Effectallowed property represents what kind of dropeffect is allowed to drag an element

The possible values for the Effectallowed property are as follows

' 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" allowed

"Link" only allows dropeffect with a value of "link"

' Move ': Only dropeffect with a value of "move" allowed

"Copylink": Allow dropeffect with values of "copy" and "link"

"Copymove": dropeffect that allow values of "copy" and "Move"

"Linkmove": dropeffect that allow values of "link" and "Move"

' All ': Allow arbitrary dropeffect

[note] The Effectallowed property must be set in the Ondragstart event handler

<div id= "Test" draggable= "true" style= "Height:30px;width:100px;background:pink;display:inline-block;" > Drag and drop source </div> <br> <div id= "Target1" style= "Margin-top:20px;height:100px;width:150px;background: Lightblue;display:inline-block; " > (none) drop target </div> <div id= "Target2" style= margin-top:20px;height:100px;width:150px;background: Lightblue;display:inline-block; " > (move) Drop target </div> <div id= "Target3" style= margin-top:20px;height:100px;width:150px;background: Lightblue;display:inline-block; " > (copy) drop target </div> <div id= "Target4" style= margin-top:20px;height:100px;width:150px;background: Lightblue;display:inline-block; " > (link) drop target </div> <div id= "result" ></div> <script>//compatible ie8-browser Test.onmousedown =function () {if (This.dragdrop) {This.dragdrop ();}} Test.ondragstart = function (e) {e = e | | event;//compatible with Firefox browser E.datatransfer.
SetData (' text ', ');
e.datatransfer.effectallowed = ' all '; } Target1.ondragenter = Target2.ondRagenter =target3.ondragenter =target4.ondragenter =function (e) {e = e | | | event; if (E.preventdefault) {E.preventdefault (
); }else{e.returnvalue = false;}
This.style.background = ' red '; } target1.ondragover = function (e) {e = e | | | event; if (E.preventdefault) {E.preventdefault ();}
else{e.returnvalue = false;} E.datatransfer.dropeffect = ' none '; } target2.ondragover = function (e) {e = e | | | event; if (E.preventdefault) {E.preventdefault ();}
else{e.returnvalue = false;} E.datatransfer.dropeffect = ' move '; } target3.ondragover = function (e) {e = e | | | event; if (E.preventdefault) {E.preventdefault ();}
else{e.returnvalue = false;} e.datatransfer.dropeffect = ' copy '; } target4.ondragover = function (e) {e = e | | | event; if (E.preventdefault) {E.preventdefault ();}
else{e.returnvalue = false;} e.datatransfer.dropeffect = ' link '; } target1.ondragleave = Target2.ondragleave =target3.ondragleave =target4.ondragleave =function (e) {e = e | | event; THIS.S
Tyle.backgroundcolor = ' lightblue '; } Target1. OnDrop = Target2.ondrop =target3.ondrop =target4.ondrop =function (e) {e = e | | event; if (E.preventdefault) {E.preventDefa
Ult (); 
}else{e.returnvalue = false;} This.style.backgroundColor = ' orange '; } </script>

The above is a small set of JavaScript to introduce the original drag and drop, I hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

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.