javascript achieves the perfect drag and drop effect

  • 2020-06-03 05:53:23
  • OfStack

The principle of drag and drop

1. Get distance (mouse position -odiv margins)

2. Understand when to use onmousemove events

3. Determine if you've crossed a line

html code:


<div id="div1"></div>

css code:


#div1{width:100px;height:100px;background:red;position:absolute}

javascript code:


window.onload=function(){
  var oDiv=document.getElementById("div1");
  var x=0;
  var y=0;
  oDiv.onmousedown=function(ev){
    var oEvent=ev||event;
    // Minus the horizontal axis of the mouse div the offsetLeft
    x=oEvent.clientX-oDiv.offsetLeft;
    // Minus the vertical axis of the mouse div the offsetTop
    y=oEvent.clientY-oDiv.offsetTop; 
     
    document.onmousemove=function(ev){
      var oEvent=ev||event;   
      var left=oEvent.clientX-x;
      var right=oEvent.clientY-y;
      // Determine if the left hand side is crossed 
      if(left<0){
        left=0;
      }
      // Determine if the right hand side is crossed 
      else if(left>document.documentElement.clientWidth-oDiv.offsetWidth){
        left=document.documentElement.clientWidth-oDiv.offsetWidth;
      }
      // Determine if the upper boundary is crossed 
      if(right<0){
        right=0;
      }
      // Check if the bottom is crossing the boundary 
      else if(right>document.documentElenment.clientHeight){
        right=document.documentElenment.clientHeight-oDiv.offsetHeight;
      }
      oDiv.style.left=left+"px";
      oDiv.style.top=right+"px";
    }   
    document.onmouseup=function(){
      // empty document In the event 
      document.onmousemove=null;
      document.onmouseup=null;
    }
    // Fix the lower version of Firefox bug , kill the system default 
    return false;
  }
}

This is the end of this article, I hope you enjoy it.


Related articles: