JavaScript implements drag-and-drop effects on PC Web pages _javascript skills

Source: Internet
Author: User

A few years ago, I was involved in the design and development of a real estate network project, I am responsible for the front-end work, because the project manager requirements are relatively high, reference to a lot of real estate sites more excellent features, want to put others more excellent design and ideas together, then the design manuscript and function to achieve, is simply changed and changed, A good effect today, may be pushed to the next day, forget it, do not say these, or to talk about the case we want to explain today, do not know that you have visited the SouFun did not (there is no advertising suspected, soufun, can give a point advertising fee does not), which has a feature product manager particularly like, that, This is the following:

This is now the effect that may have changed some, the original effect is that the inside of this picture can be dragged up and down, and then the house on the display of the building number, and then move along with the picture, then JS ability is not enough, failed to achieve the requirements of the project manager, but then the project manager again pushed off the effect, A different effect.

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

Well, that's why I wanted to write this blog today, hope to achieve this kind of drag-and-drop effect, but do not know how to achieve the students, to provide a way of thinking, not to leave the youth regret, of course, there are many ways to achieve drag-and-drop, here is only a way to introduce JavaScript, slowly realize the principle of it!

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

Drag is a container, you can use the mouse to drag around on the page to run, nonsense, the precise description should be, the mouse moved to the container, and then the mouse down, pay attention to the press, and then drag the mouse, the container can follow the mouse run, release the mouse, the container stopped there, the reality of the example is the table has a box, I put my hand on the box, and then move the box, hand stop box stop, hand away, the box does not move, hee, all understand ha!

Don't think it's a bunch of nonsense, we can get a lot of information from it, summed up as follows:

Drag = mouse down + mouse move + mouse bounce on

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

OnMouseDown, OnMouseMove, onmouseup

The code that you implement 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 general idea is there, next to consider how to let the object with the mouse to move together, the idea is probably this:

First of all, the object needs to decide the location, because we need to manipulate its left and top values in order for it to move, and then to consider the mouse, mouse movement, there will be a distance, if we know how far the mouse moved, and then put this distance to the object, that object is also the same as the mouse, Moved the same distance, this is not the implementation of drag it? Haha, a little thought, feel Meng Meng ~ Now the problem is how to get the distance of the mouse, if you need to learn more, please review the box model, here I do not say, a lot of great God also has related blog, I use a picture to express:

Description: The blue box for the screen wide, black thick box for the browser can be wide high visibility (browser reduction effect), black thin frame for the mouse to drag the object, as the figure is known, get the coordinates of the mouse, you could use Event.clientx,event.clienty to get, oh;

The approximate principle of the calculation can refer to the following figure:

Description: The left is the initial position, the right is the target position, the origin is the mouse position, large black box for the browser visual width, small black box for drag and drop objects, see drag objects to the position of the target, get the final position of the mouse, and then subtract the difference between the object of the mouse distance, and then assign value to the object's Top,left value, can also get the mouse position difference, and then with the initial top,left value plus the difference, we use the first, the second can also, to try their own:

 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 description: OnMouseMove and onmouseup Use the Document object instead of the Obj object, because if you use the Obj object, the mouse is ok inside obj, if outside of obj, drag and drop will be very strange, you can also change into obj to experience, At last we emptied the event when the mouse was bouncing;

The basic drag-and-drop above is completed, but the attentive students will certainly ask, if there is text on the page, drag the object will be selected text, 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 how to write a compatibility:

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, click on the mouse to clear the default browser, the text will not be selected, well, a simple drag-and-drop effect is completed, of course, you are now do not see the effect, the reason does not give the demo link is to let you try to write a write, so the impression is more profound,

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

If I want to achieve such an effect, is this a large container inside (can be box, also can be document), how to let our drag and drop objects do not run out, in other words, dragged to the edge will not move, 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 in a box can not run out, because there is a wall, so as long as we can simulate the wall, we will be able to frame the object, then this wall to do? We can change the idea that when the drag object is dragged to the edge, for example, drag to the right, we have its left fixed, can not go to the right, because the left value can not be added, then drag to the bottom, the same way we hold the top value, can not be dragged down, understand?

The final 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; 
};
The following
if (obj.offsettop >= pheight-oheight) {
  obj.style.top = pheight-oheight + ' px '; 

Description:pwidth,pheight represents the height of the parent element (here is the width-height limit relative to the parent), owidth,oheigt indicates the width of the drag element

Finally, I'll sort through the entire drag-and-drop code:

/* Parameter Description: element absolute positioning, relative positioning of the parent, if the parent is window, you can not pass a parameter, the parent is window, object relative to window range Drag 2 parameters, the parent is the second parameter, the object relative to the parent
      The level range Drag parameter is the ID value/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; Block 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;
          }; 
          The following if (Obj.offsettop >= pheight-oheight) {obj.style.top = pheight-oheight + ' px ';
        };
        };
          Document.onmouseup = function (EV) {var ev = EV | | | event;
        Document.onmousemove = Document.onmouseup = null;
      };
 }
         
    }

Description: The effect I handle here is that if you pass a parameter, the relative object is a Window object, if you pass 2 arguments, the first one is to drag the object, the second is the relative parent

The opening said, soufun that picture drag effect is my heart knot, I wrote a similar effect for everyone's reference, because they did not buy the server, so the effect I do not show, directly to the code posted for your reference:

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>

Javascript:

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; Block 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;
          }; 
          The following if (Obj.offsettop >= pheight-oheight) {obj.style.top = pheight-oheight + ' px ';
        };
        };
          Document.onmouseup = function (EV) {var ev = EV | | | event;
        Document.onmousemove = Document.onmouseup = null;
      };
 }
         
    }
     
     
  }

The

Effect is a block of encapsulated code that is completely used, the reference is also very convenient, some people will ask, you use the ID to get DOM elements, a page can only use once ah, if the page is used many times, there is a reason, one solution, that name different ID Bai, and not illegal, program two, Get the ID of the place to get class, but to note that, Getelementsbyclassname is to get the class set, need to rewrite, here I will not write, interested students to rewrite it, well, here is really the end!

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.