HTML5 Drag and drop (compatible with IE and non IE)

Source: Internet
Author: User

Previous life: The project needs to drag the Div, and then the position of a div to exchange, this is not the key, the key is to save the location, and then the next time you open the location to display the saved. Fortunately I have the skill deep, suddenly thought of with localstorage to save, the fact proves really good to use OH. The method of saving data has, and then began to "explore" how to use HTML (5) and JS to achieve the effect of drag and drop, because H5 to the comparison of the implementation of the standard, so easily implemented in Chrome, the evil ie (rarely scold IE) is incompatible, Nononono, heart plug, Had to use two ways to achieve the drag effect. (In fact, the code in both ways is very similar, the only difference is the name of the event, the method body is almost identical).

Present:

Let's start with a snippet of HTML code.

<body onload= "init ()" >    <div id= "content" ></div>    <div class= "Dragdiv" id= "Div1" >            </div>    <br>    <div class= "Dragdiv" id= "Div2" >            </div>    <div class= "Dragdiv" id= "Div3" >            </div>    <br>    <div class= "Dragdiv" id= "Div4" >            </div></body>

The code for the entire HTML snippet, no special place, the only thing to note is the draggable property, set to True, so you can drag him. Then, add a custom property index to each img (which can be replaced with the element tag you need) to save the order of the elements after the swap position.

JavaScript code:

 function init () {var data; $ (". Dragdiv"). each (function () {//If it is IE if (!! Window. ActiveXObject | |                         "ActiveXObject" in Windows) {$ (this). On ("DragStart", function (EV) { /* Drag to start *///Drag effect Ev.originalEvent.dataTransfer.effect                                              allowed = "Move";                        data = Ev.target.id;                    return true;                    });                    $ (this). On ("Dragend", function (EV) {return false}); $ (this). On ("DragOver", function (EV) {/* * drag element when moving on target element header */Ev.preventdefaul                        T ();                    return true;                    });                    $ (this). On ("DragEnter", function (EV) {return true;                    }); $ (tHe). On ("Drop", function (EV) {ev.preventdefault ();                        var src = document.getElementById (data);                        var srcparent = Src.parentnode;                        var tgt = Ev.currentTarget.firstElementChild;                        Replace the TGT ev.currentTarget.replaceChild (SRC, tgt) with SRC;                        Srcparent.appendchild (TGT);                        var sourceIndex = $ (src). attr ("index");                        var Targetindex = $ (TGT). attr ("index");                            There is a saved index value if (localstorage.indexs) {var indexs = Localstorage.indexs;                            Indexs = Indexs.replace (SourceIndex, "*");                            Indexs = Indexs.replace (Targetindex, "&");                            Indexs = Indexs.replace ("*", targetindex);                            Indexs = Indexs.replace ("&", SourceIndex);Save the new index order in localstorage localstorage.indexs = Indexs;                }                    }); //HTML5 's drag IE does not support else {$ (this). On ("DragOver", fun                    Ction (event) {Event.preventdefault ();                    });                        $ (this). On ("Drop", function (EV) {ev.preventdefault ();                        var src = document.getElementById (ev.originalEvent.dataTransfer.getData ("src"));                        var srcparent = Src.parentnode;                        var tgt = Ev.currentTarget.firstElementChild;                        Replace the TGT ev.currentTarget.replaceChild (SRC, tgt) with SRC;                        Srcparent.appendchild (TGT);                        var sourceIndex = $ (src). attr ("index");                        var Targetindex = $ (TGT). attr ("index");             There are saved index values           if (Localstorage.indexs) {var indexs = Localstorage.indexs;                            Indexs = Indexs.replace (SourceIndex, "*");                            Indexs = Indexs.replace (Targetindex, "&");                            Indexs = Indexs.replace ("*", targetindex);                            Indexs = Indexs.replace ("&", SourceIndex);                        Save the new index order in localstorage localstorage.indexs = Indexs;                    }                    }); $ (this). Children (0). On ("DragStart", function (event) {Event.originalEvent.dataTransfer.setData ("Sr                    C ", event.target.id);                });            }            });            The saved index value does not exist, then the Initialize if (!localstorage.indexs) {localstorage.indexs = "1,2,3,4" is saved; } else {//from the saved index values, the div var indexs = LocalStorage.indexs.toStri is displayed in orderNg (). Split (",");                    for (var i = 0; i < indexs.length; i++) {var index = indexs[i];                    var divelement = document.getElementById ("div" + index);                document.getElementById ("Content"). Insertadjacentelement ("BeforeEnd", divelement); }            }        }

  The above code is long, scary, it's OK, slowly analysis. The code is divided into two parts, namely the logic of dealing with IE and non-ie, we mainly analyze the logic of non ie (because of universal). There are three main events:
Ondragstart: Start dragging, and trigger this event when you drag the mouse over a draggable element. The ID of the element in this method that will be used to drag (swap position) is saved by SetData and used in the Dorp event.
OnDragOver: Moves to the target element when dragging.
This method has only one line of code, Event.preventdefault (), which means that the default behavior of the blocking element is not displayed, that is, the default drag-and-drop mouse hover effect.
OnDrop: When the drag-and-drop ends, release the mouse to trigger this event.
This method code a little more, mainly doing a few things.
1. The saved data is obtained by GetData, then the element elements are found and then the target element is used for Exchange;
      2. The source element and target element are replaced by the ReplaceChild method, and then the target is added back to the parent container of the source element (via the AppendChild method);
3. When you see the index attribute added to each draggable img in the HTML above, you need to get the index of the source element and target element for saving to Localstorage;
4. After you get two index, you need to remove the previously saved Indexs value from the Localstorage, and then replace the source index and target index with a special character (you can also replace it with any symbol, Mainly for the sake of simple substitution);
5. In the last step, we replace the special character of target index with source index and replace the special character of source index with target index. Then save the new Indexs value in localstorage so that our drag and save is done;

In IE, the processing, and the standard way of H5 is basically the same, the only difference is the access to SetData, and access to DataTransfer, in the above because SetData has been wrong, simply give up, directly using a local variable, Access to the DataTransfer is also given the correct use, and the other is IE on the drag behavior of the event name and H5 standard event name There are some differences, method body basically consistent.

It's not over, hahaha. We only do the saving, but load it, yes. Save is second, reloading shows the correct order is the most important.
In the Init method body we first determine whether there is already a localstorage.indexs, if not exist, we have not saved, then give him a default value it (in fact, you can not give it, anyway, after dragging or to save the amount), if there is to remove Indexs, It then splits into an array, and then iterates through the entire array, finding the corresponding div (which can be any element, not necessarily a div), and then putting it in the target Div parent container.

Well, this feature is very simple to implement in Chrome, which is the standard event, then the data is passed, saved, loaded. In IE is really enough, a variety of incompatible, all kinds of mistakes, fortunately, the final is to get out. Hope to help everyone.

HTML5 Drag and drop (compatible with IE and non IE)

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.