A deep understanding of JavaScript native drag and drop

Source: Internet
Author: User
Drag and drop (DnD) is actually two actions-drag and put. Therefore, it involves two elements. One is the dragged element, called the drag-and-drop source, and the other is the target to be put, called the drag-and-drop target. This article will introduce native drag-and-drop in detail by splitting these two concepts. If you are interested, let's take a look.

Drag and drop (DnD) is actually two actions-drag and put. Therefore, it involves two elements. One is the dragged element, called the drag-and-drop source, and the other is the target to be put, called the drag-and-drop target. This article will introduce the native drag and drop concepts in detail

Drag and Drop Source

What elements are the drag-and-drop sources?

HTML5 defines a draggable attribute for all HTML elements to indicate whether the elements can be dragged.

The draggable attribute of images and links is automatically set to true, while the default value of this attribute for other elements is false.

[Note] You must set draggable = 'true' to take effect. Only setting draggable does not work.

By default, text can be dragged only when selected, while images and links can be dragged at any time. Other elements cannot be dragged and dropped.

The link can be dragged.

The element cannot be dragged.

After setting the draggable attribute for an element, you can drag a common element.

Compatible

IE9-the browser does not support the draggable attribute, but the dragDrop () method can be called by the mousedown event handler to achieve the drag effect.

《script》test.onmousedown = function(){this.dragDrop();}《script》

[Note] If firefox supports the draggable attribute, you must add an ondragstart event handler and use the setData () method to start the effect on the dataTransfer object.

Drag and drop events

The drag-and-drop source involves three drag-and-drop events. When dragging a drag-and-drop source, trigger the events dragstart, drag, and dragend in sequence.

Dragstart

When you press the mouse key and start to move the mouse, the dragstart event is triggered on the drag-and-drop element. In this case, the cursor becomes the "cannot put" symbol (there is a backslash in the ring), indicating that the element cannot be placed on itself.

Drag

After the dragstart event is triggered, the drag event is triggered, and the event is continuously triggered during the drag of the element.

Dragend

When the drag is stopped (whether the element is put to a valid placement target or an invalid placement target), The dragend event is triggered.

0

《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

A drag-and-drop object refers to the object to be placed when the dragged element is released.

When the drag-and-drop source is dragged to the drag-and-drop target, events such as dragenter, dragover, and dragleave or drop are triggered in turn.

Dragenter

Trigger the dragenter event as long as an element is dragged to the placement target.

Dragover

The dragover event is triggered continuously when the dragged element moves within the range of the target.

Dragleave

If an element is dragged out of the position target, the dragleave event is triggered.

Drop

If an element is placed in a placement target, the drop event is triggered.

[Note] the default action of the drop event in firefox is to open the URL that is placed on the destination. To enable firefox to support normal drag and drop operations, you must also cancel the default action of the drop event.

By default, the target element is not allowed to be placed, so no drop event occurs. Only when default actions are blocked in the dragover and dragenter events can they be allowed to be placed in order to allow the occurrence of a drop event. At this time, the cursor becomes a symbol that can be placed

Drag and Drop Source

Drag and Drop target

Script var timer, I = 0; var timer1, i1 = 0; // compatible with IE8-browser test. onmousedown = function () {if (this. dragDrop) {this. dragDrop () ;}} test. ondragstart = function () {this. style. backgroundColor = 'lightgreen'; this. innerHTML = 'start dragging ';} test. ondrag = function () {if (timer) return; timer = setInterval (function () {test. innerHTML = 'the element has been dragged' ++ I + 'Second';}, 1000);} test. ondragend = function () {clearInterval (timer); timer = 0; I = 0; this. innerHTML = 'end dragging '; this. style. backgroundColor = 'pink ';} target. ondragenter = function (e) {e = e | event; if (e. preventDefault) {e. preventDefault ();} else {e. returnValue = false;} this. innerHTML = 'element enters target region'; 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 = 'the element has entered' + (++ i1) + 'second';}, 1000);} target. ondragleave = function () {clearInterval (timer1); timer1 = 0; i1 = 0; this. innerHTML = 'element has left the target region'; this. style. backgroundColor = 'lightblue';} target. ondrop = function () {clearInterval (timer1); timer1 = 0; i1 = 0; this. innerHTML = 'element has fallen into the target region'; this. style. backgroundColor = 'Orange ';} script

DataTransfer object

The dataTransfer object is introduced to implement data exchange during drag-and-drop operations. It is an attribute of the event object and is used to transmit string-format data from the dragged element to the placement target.

The dataTransfer object has two main methods: getData () and setData ()

GetData () can get the value saved by setData. The first parameter of the setData () method is also the unique parameter of the getData () method. It is a string that indicates the type of the stored data. The value is "text" or "URL"

IE only defines two valid data types: "text" and "URL", and HTML5 expands to allow various MIME types to be specified. Considering backward compatibility, HTML5 also supports "text" and "URL", but these two types are mapped to "text/plain" and "text/uri-list"

In fact, a dataTransfer object can save a value for each MIME type. In other words, saving a piece of text and a URL in this object at the same time will not cause any problems.

[Note] data stored in the dataTransfer object can only be read in the drop event handler.

When dragging text in the text box, the browser will call the setData () method to save the dragged text in the format of "text" in dataTransfer object. Similarly, when you drag and drop a link or image, the setData () method is called and the URL is saved. Then, when these elements are dragged to the target, you can read the data through getData ().

Please select some text from this pile of different mess to move to the drag-and-drop target

Drag and Drop target

Script target. ondragenter = function (e) {e = e | event; if (e. preventDefault) {e. preventDefault ();} else {e. returnValue = false;} this. innerHTML = 'element enters target region'; 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 region'; this. style. backgroundColor = 'lightblue';} target. ondrop = function (e) {e = e | event; if (e. preventDefault) {e. preventDefault ();} else {e. returnValue = false;} result. innerHTML = 'text falling into the target area: '+ e. dataTransfer. getData ('text'); this. innerHTML = 'element has fallen into the target region'; 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 transmit for future use.

Drag Source

Drag and Drop target

Script // compatible with 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 enters target region'; 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 region'; this. style. backgroundColor = 'lightblue';} target. ondrop = function (e) {e = e | event; if (e. preventDefault) {e. preventDefault ();} else {e. returnValue = false;} result. innerHTML = 'text falling into the target area: '+ e. dataTransfer. getData ('text'); this. innerHTML = 'Element already exists in the destination region'; this. style. backgroundColor = 'Orange ';} the script changes the cursor using the dataTransfer object, which not only transfers data, it can also be used to determine the elements to be dragged and what operations can be received as the elements of the targets to be placed. To this end, you need to access the two attributes of the dataTransfer object: dropEffect and effectAllowed. In fact, these two attributes are useless, but when the Drag Source moves on the drag target, the dropEffect attribute can be used to change the cursor (except in one case) to determine the placement behavior that the dragged element can perform. This property has the following four possible values: "none": the drag element cannot be placed here. This is the default value for all elements except the text box (the drop event cannot be triggered at this time) "move": move the dragged element to the target "copy ": copy the dragged element to the placed target "link": This indicates that the element to be dragged is opened when the target is placed (but the dragged element must be a link with a URL) when you drag an element to the target, each value above will cause the cursor to be displayed as a different symbol [note] the dropEffect attribute inclutallowed dropEffect must be set for the placement destination in the ondragover event handler. This attribute is only useful when used with the inclutallowed attribute. The inclutallowed attribute indicates which dropEffect inclutallowed attribute of the element to be dragged. The possible values are as follows: "uninitialized": no placement behavior is set for the dragged element "none ": the dragged element does not have any behavior. "copy": Only dropEffect "link" with a value of "copy" is allowed. dropEffect "move" with a value of "link" is allowed ": only dropEffect "copyLink" with a value of "move" is allowed: dropEffect "copyMove" with a value of "copy" and "link ": dropEffect "linkMove" with values "copy" and "move": dropEffect "all" with values "link" and "move ": to allow any dropEffect [note], you must set the deletallowed attribute in the ondragstart event handler.

Drag and Drop Source


(None) drag and drop target

(Move) drag and drop the target

(Copy) drag and drop target

(Link) drag-and-drop target

Script // compatible with 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. export tallowed = '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. style. backgroundColor = 'lightblue ';} target1.ondrop = target2.ondrop = target3.ondrop = target4.ondrop = function (e) {e = e | event; if (e. preventDefault) {e. preventDefault ();} else {e. returnValue = false;} this. style. backgroundColor = 'Orange ';} script

The above is the JavaScript native drag-and-drop introduced by xiaobian. I hope it will help you. If you have any questions, please leave a message and I will reply to you in time. I would like to thank you for your support for PHP chinnet!

For more information about native JavaScript drag-and-drop, please refer to the PHP Chinese website!

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.