JavaScript small instance, drag and drop in PC Web page

Source: Internet
Author: User

This is now the effect, may have changed some, the original effect is that the inside of this picture can be dragged up and down, and then the house above the display of the building number, but also with the picture moved, then JS ability is not enough, failed to achieve the project manager's requirements, but then the project manager to push off the effect, For another effect.

Although the project manager did not want this effect, but at that time in my heart left a section, to today can not forget the stem.

Well, this is my intention to write this blog today, hoping to achieve this kind of drag-and-drop effect, but do not know how to achieve the students, to provide a way of thinking, do not give the youth to regret, of course, there are many ways to achieve drag and drop, here is only a way to introduce JavaScript, slowly experience the principle of it!

Well, the stem is also said, start the subject, we have to understand, drag in the end is a thing, you know, I also know, but I still want to describe:

Drag is a container, you can use the mouse to drag around the page everywhere, nonsense, the precise description should be, the mouse moved to the container, and then mouse down, attention to do not put, and then drag the mouse, the container can follow the mouse to run, release the mouse, the container stopped there, the real example is a box on the table, I put my hands on the box, and then move the box, the hands Stop the box stop, hands open, the box does not move, hehe, all understand ha!

Do not think that said a bunch of nonsense, we can get a lot of information, summarized as follows:

Drag = Mouse Press + mouse move + mouse bounce on

This completes a drag-and-drop task, OK, this is the drag-and-drop principle, want to implement drag and drop, the natural implementation of the above 3 actions, you can simulate the drag effect, good, the corresponding JavaScript syntax is the need to implement these 3 actions:

OnMouseDown, OnMouseMove, onmouseup

The code that is implemented should be:

Obj.onmousedown = function (ev) {      obj.onmousemove = function (EV) {       };      Obj.onmouseup = function (EV) {            };     }

  

Why the back 2 action to write inside, a good aftertaste, well, the first step of the approximate idea has, the next step is to consider how to let the object with the mouse to move together, the idea is probably this:

First, the object needs to determine the positioning, because we need to manipulate its left and top values, in order to let it move, and then is to consider the mouse, mouse displacement, itself will have a distance, if we know how far the mouse moved, and then the distance to the object, that object is not also the same as the mouse, Move the same distance, does this not implement drag and drop? Haha, the idea a little bit, feel the big ~ Now the problem is how to get the distance of the mouse, if you need to understand, please review the box model, here I do not say, many great God also has related blog, I use a picture to represent:

Description: Blue box for the screen height, black thick box for the browser visibility area width high (browser zoom out effect), the black thin box for the mouse to drag the object, know, get the mouse coordinates, can use Event.clientx,event.clienty to get, oh;

The approximate principle of calculation can be referred to:

Description: The left is the initial position, the right is the target position, the origin is the mouse position, the big black box for the browser visual width, the small black box for the drag object, see Drag the object to the target position of the state, get the final position of the mouse, minus the mouse distance object difference, and then assign to the object's Top,left value, You can also get the position difference of the mouse, and then use the initial Top,left value plus the difference, we use the first, the second can also, try it yourself:

Obj.onmousedown = function (ev) {    var ev = EV | | event;    var disx = Ev.clientx-this.offsetleft,disy = Ev.clienty-this.offsettop;     Document.onmousemove = function (ev) {        var ev = EV | | event;        Obj.style.left = ev.clientx-disx + ' px ';        Obj.style.top = Ev.clienty-disy + ' px ';    };    Document.onmouseup = function (ev) {        var ev = EV | | event;        Document.onmousemove = Document.onmouseup = null;    };}

  

Here's a note: OnMouseMove and onmouseup Use the Document object instead of the Obj object because if you use the Obj object, the mouse is okay inside obj, and if it's outside of obj, the drag will be weird, you can change it to obj, Finally, we empty the event when the mouse bounces up;

The above basic drag even completed, but the careful classmate will ask, if the page has text, drag the object will be selected, this effect is not strange, yes, this is because the drag and drop triggered the browser's default selection event, so, in the drag, we want to clear this default event, How do you get rid of it?

Here's a compatibility notation:

if (ev.stoppropagation) {     ev.stoppropagation ();} else{    ev.cancelbubble = true;//compatible ie}//abbreviated to ev.stoppropagation? Ev.stoppropagation (): Ev.cancelbubble = true;

  

Put the above code under the onmousedown, the mouse button to clear the browser default event, the text will not be selected, well, a simple drag effect is completed, of course, you are now not see the effect, the reason is not to give the demo link is to let you try to write a write, so the impression is more profound,

Well, that's the question again, is it over here? According to my style, of course no, dry goods are still in the back!

If I want to achieve such an effect, it is this large container (can be box, also can be document), how can let our drag object not to run out, in other words, drag to the edge of the drag, yes, is not a lot of people want to achieve the effect, haha, Let's see what the implementation principle is:

In real life, an object can not run out in a box, because there is a wall, then we can simulate this wall, we could put the object frame, then how to do this wall? We can change the idea, when dragging the object to the edge, such as drag to the right, we will its left fixed, is not able to go to the right, because the left value can not be added, then drag to the bottom, similarly we will top value fixed, we can not drag down, understand?

The end result is as follows:

Left if (Obj.offsetleft <=0) {    obj.style.left = 0;};/ /Right if (Obj.offsetleft >= pwidth-owidth) {    Obj.style.left =  pwidth-owidth + ' px ';  };/ /above if (obj.offsettop <= 0) {    obj.style.top = 0;};//under if (obj.offsettop >= pheight-oheight) {    obj.style.top =  pheight-oheight + ' px ';};

  

Description: Pwidth,pheight represents the width of the parent element (here is the width-height limit relative to the parent), and owidth,oheigt represents the width of the dragged element

Finally, I've collated the entire drag code:

/* Parameter Description: The absolute positioning of the element, the parent relative positioning, if the parent is window, you can not pass a parameter, indicating that the parent is window, the object relative to the window range drag 2 parameter, the parent is the second parameter, and the object is dragged relative to the parent range as an ID value */function drag (obj,parentnode) {var obj = Document.g            Etelementbyid (obj);                  if (arguments.length = = 1) {var parentnode = window.self;               var pWidth = Parentnode.innerwidth,pheight = Parentnode.innerheight;                }else{var parentnode = document.getElementById (parentnode);            var pWidth = Parentnode.offsetwidth,pheight = Parentnode.offsetheight;                } Obj.onmousedown = function (EV) {var ev = EV | | event;                var disx = Ev.clientx-this.offsetleft,disy = Ev.clienty-this.offsettop;                                 var owidth = Obj.offsetwidth,oheight = Obj.offsetheight; Stop bubbling Time ev.stoppropagation?            Ev.stoppropagation (): Ev.cancelbubble = true;                                  Document.onmousemove = function (EV) {var ev = EV | | event;                    Obj.style.left = ev.clientx-disx + ' px ';                                         Obj.style.top = Ev.clienty-disy + ' px ';                    Left if (Obj.offsetleft <=0) {obj.style.left = 0;                    };  Right if (obj.offsetleft >= pwidth-owidth) {obj.style.left = Pwidth-owidth                      + ' px ';                    };                     Above if (obj.offsettop <= 0) {obj.style.top = 0;                    }; Below if (obj.offsettop >= pheight-oheight) {obj.style.top = Pheight-oheig                     HT + ' px ';                };                };                 Document.onmouseup = function (EV) {var ev = EV | | event;   Document.onmousemove = Document.onmouseup = null;            }; }                         }

Description: The effect I deal with here is that if a parameter is passed to indicate that the relative object is a Window object, if 2 arguments are passed, the first one is the dragged object and the second is the relative parent

Css:

<style>.box{    width:600px;    height:400px;    margin:50px Auto;    position:relative;    Overflow:hidden;} #box {    width:1000px;    height:800px;    Position:absolute;    left:50%;    top:50%;    margin:-400px 0 0-500px;} #pic {width:800px; height:600px; Background:url (images/pic1.jpg) no-repeat; position:absolute; left:100px; top:100px;} #pic: hover{    cursor:move;} </style>

Html:

<div class= "box" >        <div id= "box" >            <div id= "pic" ></div>        </div>    </div>

Js:

Window.onload = function () {drag ("Pic", "box");            function drag (obj,parentnode) {var obj = document.getElementById (obj);                  if (arguments.length = = 1) {var parentnode = window.self;               var pWidth = Parentnode.innerwidth,pheight = Parentnode.innerheight;                }else{var parentnode = document.getElementById (parentnode);            var pWidth = Parentnode.offsetwidth,pheight = Parentnode.offsetheight;                } Obj.onmousedown = function (EV) {var ev = EV | | event;                var disx = Ev.clientx-this.offsetleft,disy = Ev.clienty-this.offsettop;                                 var owidth = Obj.offsetwidth,oheight = Obj.offsetheight; Stop bubbling Time ev.stoppropagation?                                              Ev.stoppropagation (): Ev.cancelbubble = true; Document.onmousemove = function (EV) {var ev = EV | | event;                   Obj.style.left = ev.clientx-disx + ' px ';                                         Obj.style.top = Ev.clienty-disy + ' px ';                    Left if (Obj.offsetleft <=0) {obj.style.left = 0;                    };  Right if (obj.offsetleft >= pwidth-owidth) {obj.style.left = Pwidth-owidth                      + ' px ';                    };                     Above if (obj.offsettop <= 0) {obj.style.top = 0;                    }; Below if (obj.offsettop >= pheight-oheight) {obj.style.top = Pheight-oheig                     HT + ' px ';                };                };                    Document.onmouseup = function (EV) {var ev = EV | | event;                Document.onmousemove = Document.onmouseup = null;            };   }                         }                   } 

The effect is completely with the package code block, quoted is also very convenient, some people will ask, you use the ID to get DOM elements, a page can only be used once ah, if the page is used more than once, there is a reason, one solution, then the name of a different ID Bai, and not illegal, program two, Get the ID of the place to get the class, but note that Getelementsbyclassname is the class collection, need to rewrite, here I do not write, interested students to rewrite it, well, to the end of the really!

JavaScript small instance, drag and drop (turn) in PC Web page

Related Article

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.