Home > Web Front-end > JS Tutorial > Javascript achieves perfect drag and drop effect_javascript skills

Javascript achieves perfect drag and drop effect_javascript skills

WBOY
Release: 2016-05-16 16:00:50
Original
1269 people have browsed it

The principle of drag and drop

1. Get the distance (mouse position - odiv margin)

2. Understand when to use onmousemove event

3. Determine whether it has crossed the boundary

html code:

<div id="div1"></div>
Copy after login

css code:

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

Copy after login

javascript code:

window.onload=function(){
  var oDiv=document.getElementById("div1");
  var x=0;
  var y=0;
  oDiv.onmousedown=function(ev){
    var oEvent=ev||event;
    //鼠标的横坐标减去div的offsetLeft
    x=oEvent.clientX-oDiv.offsetLeft;
    //鼠标的纵坐标减去div的offsetTop
    y=oEvent.clientY-oDiv.offsetTop; 
     
    document.onmousemove=function(ev){
      var oEvent=ev||event;   
      var left=oEvent.clientX-x;
      var right=oEvent.clientY-y;
      //判断左边是否过界
      if(left<0){
        left=0;
      }
      //判断右边是否过界
      else if(left>document.documentElement.clientWidth-oDiv.offsetWidth){
        left=document.documentElement.clientWidth-oDiv.offsetWidth;
      }
      //判断上边是否过界
      if(right<0){
        right=0;
      }
      //判断下边是否过界
      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(){
      //清空document的事件
      document.onmousemove=null;
      document.onmouseup=null;
    }
    //解决低版本火狐bug,干掉系统默认
    return false;
  }
}
Copy after login

The above is the entire content of this article, I hope you all like it.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template