First on the Demo, try to use Chrome, the code can refer to Github.
Before HTML5, the drag-and-drop of page elements requires listening to a series of events such as MouseDown, MouseOver, and MouseUp, and then changing the relative position of the elements to achieve this effect. The advent of the HTML DnD (drag-and-drop) API makes drag and drop simple. However, since DnD is still in the draft stage, browsers do not unify their specifications, and some events may have different effects in different browsers.
To use DnD, you need to be clear about two things, one is the element you want to drag, and the other is where you can place the dragged element. Drag and drop is nothing more than dragging an element from one location to another.
Drag
First we need to specify the element to drag, which is easy to set, set the property to the DOM element draggable
, and set the property value to true
. such as this:
Copy Code<img src=‘images/0.jpg‘ draggable=‘true‘ id=‘img0‘ />
In fact, the above code is superfluous, the picture (IMG) on the page, the link (a tag with href), and the text by default are draggable. For unification, it is best to add the Draggable attribute as well.
draggable
Property also has two values, respectively, false
and, as the auto
name implies, false is set to non-draggable, auto is the browser default value.
When we left-click (Press) a draggable DOM element and move it lightly, it triggers the ondragstart
event, which only fires once. Usually we record the element information that is being dragged in the ondragstart event (it is good to handle it when ondrop). For example, the ID of the element being dragged is recorded in the demo:
Copy Codefor (var i = lis.length; i--; ) { lis[i].ondragstart = function(e) { e.dataTransfer.setData(‘id‘, e.target.id); };}
After the ondragstart event is triggered, the event is triggered until the drag-and-drop event ends ondrag
.
Drop
Next we need to specify where the dragged element can be placed, and ondragover
where the event specifies where the dragged data will be placed.
By default, elements cannot be placed in other elements, and if you need to set allow placement, we must block the default handling of elements:
Copy Codevar dus = document.querySelector(‘.dustbin‘);dus.ondragover = function(e) { e.preventDefault();};
When an element is dragged onto an element, the latter's event is triggered, and the ondrop
ondrop
default behavior of some DnD events needs to be canceled if the event needs to be triggered correctly:
Copy Codefunction(e) { // 调用 preventDefault() 来避免浏览器对数据的默认处理(drop 事件的默认行为是以链接形式打开) e.preventDefault(); e.stopPropagation(); // 兼容ff var id = e.dataTransfer.getData(‘id‘) , node = document.getElementById(id); node.parentNode.removeChild(node);};
Some documents say to cancel ondragenter()
the default behavior of the event, landlord in the actual operation did not find this.
Event
The above mentioned three events in DnD, and, in dragstart
dragover
drop
fact, DND has several events, the order of their occurrence is:
Copy Codedragstart(drag元素) -> drag(drag元素) -> dragenter(drop元素) -> dragover(drop元素) -> dragleave(drop元素) -> drop(drop元素) -> dragend(drag元素)
It is not difficult to understand that the drag-and-drop event starts when the Ondragstart event is triggered and the OnDragEnter event is triggered when the dragged element enters the element that can be placed (OnDragEnter is not triggered when the two elements intersect. Instead, the drag element moves over the target element for a period of time before it is triggered, and then an event continues to trigger the OnDragOver event (refer to MouseOver), triggering ondragleave (and OnDragEnter) when the dragged element leaves the element that can be placed. event, which triggers the OnDrop event when the mouse is released and the dragged element is just on the element that can be placed, triggering the ondragend (and ondragstart corresponding) event at the end of the drag-and-drop event, which is triggered regardless of the success of the drag-and-drop operation.
DataTransfer
During the drag process, the callback function accepts an event argument that has a DataTransfer property. It points to an object that contains various information related to the drag.
There are two main methods of DataTransfer objects: GetData () and SetData (), and it is important to note that only the dragstart
two methods are used in the and drop
events. It is not difficult to imagine that getData () can obtain a value saved by SetData (). The first parameter of the SetData () method, which is also the only parameter of the GetData () method, is a string that represents the saved data type, with a value of ' text ' or ' URL '. IE only defines two valid data types: ' Text ' and ' URL ', and HTML5 expands it to allow for the various MIME types to be specified.
When you drag the text in the text box, the browser automatically calls the SetData () method, saves the dragged text in the ' text ' format in the DataTransfer object, and similarly, when you drag and drop the link or image, it automatically calls SetData () to save the URL information, if necessary, You can use GetData () to read the values saved by the browser in the drop event.
But this does not seem to be an egg, we are in the actual development of the majority of the DOM operation, so in most cases we call SetData () in the DragStart event handler, manually save the data we want to transfer, and then read in the drop event, a bit like the JQuery Data event.
DropEffect and effectallowed
dropEffect
And the effectAllowed
two attributes of the object mentioned earlier dataTransfer
, what's the use? In short, there are two uses, one can set the element is dragged when the mouse style, the second is to set whether the element can be placed.
Here I tested three browsers with Chrome, FF and Uc,chrome and UC behaving similarly.
In general, we leave the element in its original position, and the mouse gesture becomes a "no hand" until the element is dragged onto the area where it can be placed.
But FF otherwise, in FF, the element does not show "no hands" during the drag process.
The default mouse gesture is as follows when the element is dragged onto a removable area.
In fact, by setting dropEffect
and effectAllowed
a total can set three mouse gestures (move, copy, and link), respectively (move and default looks like):
You need to ondragstart
set effectallowed in the method and ondragover
set DropEffect in the method. Refer to the demo code for details.
We can also set the values of DropEffect and effectallowed so that a drop element can only be placed on a move element, or a copy element. Specifically, you can look at this article, HTML5 Magic Hall: A comprehensive understanding of drag & Drop API, very good. You can also refer to the Elevation 484 page for a value.
To be sure, DnD does not help you with any action of copy or move, but rather requires the user to record the object information that needs to be manipulated during the DND process, and then complete the actions of copy or move in the drop event.
Tricks
There are several problems that are found in the practice process.
Opening the Demo in FF and dragging the picture to Gouges will automatically open the picture in the new tab, although I have added Preventdefault () to the various events, it is unclear why.
If you can drag the element, initially in a can be placed inside the element, first drag the element out, and then put back, will trigger the OnDrop event, but E.target is dragged elements. If placed in another element, target points to the placed element instead of dragging the element. This can be resolved by judging the target element. This can be seen in the W3cschool demo, open the console, drag the picture out, and then drag back, the console will print errors, obviously the code does not take this into account.
Read MORE:
- HTML 5 Drag and drop
- HTML5: Full understanding of Drag & Drop API
- HTML5 drag-and-drop API
- HTML5 drag-and-drop operations API and examples
html5-let the drag and drop become popular.