Use HTML5 Native drag events (drag) to achieve drag effects

Source: Internet
Author: User

Drag effect believe that many friends have written their own, whether you use the original JS or jquery to achieve it is very simple, but today I would like to introduce the use of the HTML5 standard defined in the native drag events to achieve the drag effect.

First, background:

    In fact, it is HTML5 standard definition, in fact, the earliest IE4 in the drag-and-drop API, just in IE4, only two objects in the Web page can be dragged and dropped: images and some text. And the only valid drop target in IE4 is the text box. By the IE5.5, drag-and-drop functionality has been extended to allow any element in the page to be dragged and dropped. Finally, HTML5 based on the power of IE to develop drag and drop specifications. Ff3.5+,safari3+ and Chrome implement native drag-and-drop based on specifications.

Ii. Events:

The events involved in native drag-and-drop are divided into the following two phases:

     (1) When you drag an element, the stage triggers the following event (the event target for that stage-that is, target or srcelement is the dragged element):

         1>dragstart--mouse moves into the target element and presses the left button to trigger.

2>drag--dragstart triggers the event (similar to the MouseMove event) by moving the mouse after triggering

3>dragend--triggered when drag is stopped (whether the dragged element is in a valid or invalid position at this time).

     (2) When an element is dragged onto a valid drop target, the following events are triggered (the target element for the event target-that is, Target or srcelement):

1>dragenter--trigger DragEnter event (similar to mouseover) whenever an element is dragged onto a drop target

2>dragover--triggers the event when it moves within the active target range after triggering DragEnter

3>dragleave--triggered when a dragged element is dragged outside the target range from the target range

4>drop--the dragged element is placed in the target range (i.e., the left mouse button in the active target range)

           Note: Here DragLeave and drop can only trigger one!

 Third, define the location of the drop:

     Although all elements support drop target events, these elements are not allowed by default and cannot trigger a drop event if the dragged element passes through an element that is not allowed to be placed. So we have to define the target element of the placement first.

    Defining the target element is also simple, as long as the default behavior of the DragEnter and DragOver events is blocked, assuming our target element is a DIV with an ID of Drag-area, we want to define it as our target element, just the following code:

Drag_area.ondragover=function(EVT) {//Default event to block DragOver        varevt=evt | |window.event; if(typeofevt.preventdefault== "function") {evt.preventdefault (); }Else{Evt.returnvalue=false; }} drag_area.ondragenter=function(EVT) {//Default event to block DragEnter        varevt=evt | |window.event; if(typeofevt.preventdefault== "function") {evt.preventdefault (); }Else{Evt.returnvalue=false; }    }

(a small partner may ask, AH ~ Prevent default events can not be directly used to return false, why so troublesome. Indeed, return false prevents the default events and events from propagating, and I have tested, with return false, and indeed can achieve the same effect. Here is mainly a Firefox problem, my Firefox is the latest version, directly with return false no problem, but according to http://blog.csdn.net/goldlevi/article/details/ 5721348 said that earlier versions of Firefox if DragEnter and DragOver did not set the preventdefault will not trigger the drag event on the element, steal a lazy, do not test other Firefox yourself ~ There is one more question about FF, which will be mentioned later);

Four. Implement

Before explaining the custom drop target, here the specific implementation is not much to say (in fact, the principle and ordinary implementation of almost ~) directly on the code:

<! DOCTYPE html>#drag-area{width:500px;height:500px;            border:1px solid red;        position:relative; } #my-img{Position:absolute; }    </style>varMy_img=document.getelementbyid ("My-img"); varDrag_area=document.getelementbyid ("Drag-area"); My_img.ondragstart=function(EVT) {//get coordinates cheaply in the DragStart event of the dragged element        varevt=evt | | window.event;//that is, Evt.clientx-this.offsetleft and evt.clienty-this.offsettop in the code, and saved in the DataTransfer objectEvt.dataTransfer.setData ("Text", (evt.clientx- This. offsetleft) + ";" + (evt.clienty- This. OffsetTop)); } drag_area.ondragover=function(EVT) {//Default event to block DragOver        varevt=evt | |window.event; if(typeofevt.preventdefault== "function") {evt.preventdefault (); }Else{Evt.returnvalue=false; }} drag_area.ondragenter=function(EVT) {//Default event to block DragEnter        varevt=evt | |window.event; if(typeofevt.preventdefault== "function") {evt.preventdefault (); }Else{Evt.returnvalue=false; }} Drag_area.ondrop=function(evt) {varevt=evt | |window.event; varDrag_data=evt.datatransfer.getdata ("Text"). Split (";");//Extracts data from the DataTransfer object and splits the string into an array        varOffset_x=drag_data[0],//Get horizontal offsetOFFSET_Y=DRAG_DATA[1];//Get vertical offset        if(typeofevt.preventdefault== "function") {//default behavior to prevent drop eventsEvt.preventdefault (); }Else{Evt.returnvalue=false; } my_img.style.left= (evt.clientx-offset_x) + "px";//Assigning a left,top to a dragged elementMy_img.style.top= (evt.clienty-offset_y) + "px"; }</script>

The code qualifies the dragged element (my_img) to be dragged only within the (Drag_area) 500*500 Div. In the code we took the DragStart event of the drag-and-drop element with the coordinate offset of the mouse click Evt.clientx-this.offsetleft and evt.clienty-this.offsettop and then stored it in the DataTransfer object,

The offset value is then removed from the DataTransfer object in the drop event of the target element to calculate the left and top of the dragged element.

Explain the object under datatransfer . This object is a property of the event object, and we typically use it to set its value in the DragStart event handler of the dragged element (such as the My_img in code), the drop event in the target element (Drag_area in code) (and only in the drop event ), in addition, the browser automatically stores the dragged text (URL) in the object as we drag the text (Picture/link).

   The syntax for setting datatransfer content is as follows:

Event.dataTransfer.setData ("Data Type", "value")--here the data type although HTML defines a variety of mime types, it is best to use only the

'text'-Save string and 'URL'-save URL (ie only defines these two types);

The value of course is the value you need.

The syntax for extracting data from the DataTransfer object is as follows:

Event.dataTransfer.getData ("Data Type")--here the data type is the same as the data type in SetData.

Another DataTransfer object has two properties, DropEffect and effectallowed. But personally feel very chicken, not much to say, just changed the mouse style has wood ah ~

Well, interested students to change the picture link to try it ~ This method compatibility: Opera does not support no words, no problem in ie6+,chrome, but dragging the picture in the FF automatically opens the URL of the picture, and can not be blocked (the drop event in the code has blocked the default code ~ Beta versions ff31.0 and ff32.03) =_=! No science at all. Hope to see this article, there is a solution to the message of the great God.

Summing up, although we use MouseDown, MouseMove, MouseUp can also be convenient to make drag and drop effect, and there is no compatibility above said and FF bug, but if the project does not need to be compatible with opera, and is dragging the selected text, This method is more convenient (as mentioned above, the drag-and-Drop text browser will automatically place the selected and dragged text, the URL is stored in the DataTransfer object). And, do the front-end is not toss it ....

Use HTML5 Native drag events (drag) to achieve drag effects

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.