Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="description" content="一个面向对象的拖拽demo">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    #drag{
      width: 40px;
      height: 40px;
      position: absolute;
      background-color: red;
      cursor:pointer;
    }
  </style>
</head>
<body>
  <div id="drag">
  </div>
</body>
<script>
  function Drag(name){
    this.drag =  document.getElementById(name);
    this.x=0;
    this.y=0;
  }
  Drag.prototype.init = function(){
    var This = this;
    this.drag.onmousedown = function(ev){
      var ev = ev || window.event;
      This.fnDown(ev);
      return false;
    }
  }
  Drag.prototype.fnDown = function(ev){
    var This = this;
    this.x = ev.clientX-this.drag.offsetLeft;
    this.y = ev.clientY-this.drag.offsetTop;
    document.onmousemove = function(ev){
      var ev = ev || window.event;
      This.fnMove(ev);
    };
    document.onmouseup = this.fnUp;
  }
  Drag.prototype.fnMove = function(ev){
    var nowx= ev.clientX-this.x;
    var nowy= ev.clientY-this.y;
    console.log(nowx);
    this.drag.style.left = nowx + 'px';
    this.drag.style.top = nowy + 'px';
  }
  Drag.prototype.fnUp = function(){
    document.onmousemove = null;
    document.onmouseup = null;
  }
  var drags = new Drag('drag');
  drags.init();
</script>
</html>
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
buxukupro
0viewers