A draggable div

Source: Internet
Author: User

When doing Web UI design, dragging an HTML element has become a kind of user interface pattern that can not be neglected, the typical application example is dialog, how does an element implement drag? In fact, the principle is very simple, to achieve the first to understand a few basic knowledge.

Tips

Absolute Positioning: only the Position property of the element is set to absolute and the fixed can be dragged, by default the element will determine its location on the page by its position in the document flow, and it cannot be moved. While an absolutely positioned element can leave an element out of the document flow, relative to its positioned parent element or screen positioning, you can use craved to implement element dragging by altering the displacement of the element to the positioned parent element. About positioning knowledge you can look at CSS layouts--from display,position, float properties.

Mouse events: When the mouse is pressed, moved, pop up will trigger the corresponding event, when the mouse button will also trigger the corresponding element click event, and bubbling to document, mentioned above to change the element and positioning the parent container displacement can be implemented in these events. About event-related knowledge you can see how JavaScript interacts with HTML-events

The dialog to drag

Write a simple dialog for the drag test to use

<!            DOCTYPE html>

Looks like it's jiangzi.

Drag a bit

For the sake of simplicity, there is no browser compatibility issue to be taken care of, first based on chrome implementation. The above dialog is the document, the mouse event object contains the Clientx and Clienty two properties, identifies the mouse current relative viewport (visual window) position, You can change dialog's left and top property values to move as you move.

var Isdialogtitle=false;                        function Down (e) {                if (e.target.classname.indexof (' Dialog-title ')!=-1) {                    isdialogtitle=true;                }            }                        function Move (e) {                var Dialog=document.getelementbyid (' Dlgtest ');                if (isdialogtitle) {//Only click Dialog title to drag                    dialog.style.left=e.clientx+ ' px ';                    dialog.style.top=e.clienty+ ' px ';                }            }                        function up (e) {                isdialogtitle=false;            }                        Document.addeventlistener (' MouseDown ', down);            Document.addeventlistener (' MouseMove ', move);            Document.addeventlistener (' MouseUp ', up);

This drag effect is implemented, in order to ensure that only the mouse click Dialog title when the drag, when the mouse pressed to determine the event source, if it is the dialog title area, the Isdialogtitle tag is set to True, When the mouse moves the first to Judge Isdialogtitle, when the mouse bounces off the mark set to False.

One jump, one jump.

The students who have tried the demo in person will certainly be able to jump when they start to move, what is the situation with dialog? Take a closer look at the code found in the mobile initial, the code will dialog left and top set to the current position of the mouse, but the user in the drag will not deliberately go to point dialog the upper left corner, so jump, soga! A little bit better

var draggingobj=null;            Dragging Dialog var diffx=0;                        var diffy=0; function Down (e) {if (E.target.classname.indexof (' Dialog-title ')!=-1) {Draggingobj=e.targ                    Et.offsetparent;                    Diffx=event.clientx-draggingobj.offsetleft;                Diffy=event.clienty-draggingobj.offsettop;                }} function Move (e) {var Dialog=document.getelementbyid (' Dlgtest ');                    if (draggingobj) {//Only click Dialog title to drag dialog.style.left= (E.CLIENTX-DIFFX) + ' px ';                Dialog.style.top= (E.clienty-diffy) + ' px ';                }} function up (e) {draggingobj=null;                diffx=0;            diffy=0;            } document.addeventlistener (' MouseDown ', down);            Document.addeventlistener (' MouseMove ', move); Document.addevenTlistener (' MouseUp ', up); 
Good red fruit fruit

After the change no longer jump, but very exposed to the feeling, the first definition of the three variables are exposed to the window, and this kind of writing is quite non-universal, in case the dialog title changed later, generally used this method of the place have to be changed once, in case the title inside there are child elements, What do I do when I click on its child elements? In that case, put on a suit and wrap it

var dragging=function (Validatehandler) {//parameter to verify that the hit area is a movable area, if it is returned to move the element, is responsible for returning the null var draggingobj=null;//dra                Gging Dialog var diffx=0;                                var diffy=0;                            function Mousehandler (e) {switch (e.type) {case ' MouseDown ':                                Draggingobj=validatehandler (e);//Verify whether the clickable Move area if (draggingobj!=null) {                                Diffx=e.clientx-draggingobj.offsetleft;                            Diffy=e.clienty-draggingobj.offsettop;                                                } break; Case ' MouseMove ': if (draggingobj) {draggingobj.style.left= (e.cli                                ENTX-DIFFX) + ' px ';                            Draggingobj.style.top= (E.clienty-diffy) + ' px ';                       } break;                         Case ' MouseUp ': Draggingobj =null;                            diffx=0;                            diffy=0;                    Break                                }                };                         return {enable:function () {document.addeventlistener (' MouseDown ', mousehandler);                        Document.addeventlistener (' MouseMove ', mousehandler);                    Document.addeventlistener (' MouseUp ', mousehandler);                        }, Disable:function () {document.removeeventlistener (' MouseDown ', mousehandler);                        Document.removeeventlistener (' MouseMove ', mousehandler);                    Document.removeeventlistener (' MouseUp ', mousehandler); }                }            }

Packaging It really looks much better, the code is not ugly understand, there are a few points of note, dragging function Validatehandler parameter is not what puppy, as the comments said in order to solve the problem of several requirements change mentioned, Validatehandler is a handle to a custom function, which is used to identify whether the clicked element triggers a move, or if it needs to be returned to move the element, so that it is possible to trigger the movement flexibly and decide to move the element (the clicked and moving is not necessarily a). The dragging function returns an object with two methods that allow the element to be moved/disabled and to see how it is used

function Getdraggingdialog (e) {                var target=e.target;                while (Target && target.className.indexOf (' Dialog-title ') ==-1) {                    target=target.offsetparent;                }                if (target!=null) {                    return target.offsetparent;                } else{                    return null;                }            }                        Dragging (Getdraggingdialog). Enable ();

First define a recognition function, then call the dragging function as a parameter and invoke the Enable method of the return value so that the element can be dragged.

Source
<!            DOCTYPE html>The shortcomings

This kind of drag-and-drop approach looks good, but there are a few more regrets.

1. Previously mentioned browser compatibility issues, this writing in the low version of IE browser is not operational

2. Boundary check, careful classmate found dialog not only can drag, but also can make the page scroll bar infinite drag, most of the circumstances we want to dialog in the Visual window, document (within the inherent scroll bar) or fixed area drag, this way does not do this limit

3. Drag, in this demo does not appear this problem, the document structure simple drag smooth, visible in the huge page if the mouse moves too fast, dialog will keep up with the mouse, there is a lag, this time if the mouse outside the dialog, MouseUp event will not take effect, drag will not stop , you can only move the mouse back to dialog in MouseUp

A draggable div

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.