拖拽面向对象的写法

<!---css部分--->

#div1{
  200px;
  height: 300px;
  position: absolute;  //要实现拖拽需要把div设置为拖动层
  background: red;
}

#div2{
  200px;
  height: 300px;
  position: absolute; //要实现拖拽需要把div设置为拖动层
  background: green;

  top: 300px;

}

<!---html部分--->

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

<!--script-->

function Drag (id) {

  var _this = this;
  this.disX = 0;
  this.disY = 0;
  this.oDiv = document.getElementById(id);
    this.oDiv.onmousedown = function (ev) {  // 这里需要保存下ev以便给火狐使用
    _this.fnDown(ev); // 这里需要保存下ev以便给火狐使用
   };
}

  Drag.prototype.fnDown = function (ev) {
    var _this = this;
    var oEvent = ev || event;
    this.disX = oEvent.clientX - this.oDiv.offsetLeft;    // oEvent.clientX 获得当前鼠标所在X位置   this.oDiv.offsetLeft 获得当前位置浮动的left值
    this.disY = oEvent.clientY - this.oDiv.offsetTop;    // oEvent.clientY 获得当前鼠标所在Y位置   this.oDiv.offsetTop 获得当前位置浮动的top值

    document.onmousemove = function (ev) {
      _this.fnMove(ev);
    };

   document.onmouseup = function () {
     _this.fnUp();
   };
};

  Drag.prototype.fnMove = function (ev) {

    var oEvent = ev || event;
    this.oDiv.style.left = oEvent.clientX - this.disX + 'px';     // oEvent.clientX 获得当前鼠标所在X位置   this.disX 获得当前浮动层原来的x位置
    this.oDiv.style.top = oEvent.clientY - this.disY + 'px';    // oEvent.clientX 获得当前鼠标所在X位置   this.disY 获得当前浮动层原来的Y位置
  };


  Drag.prototype.fnUp = function () {
    document.onmousemove = null;
    document.onmouseup = null;
 };

 window.onload = function () {
   new Drag('div1');
   new Drag('div2');
 };

<!--script-->

原文地址:https://www.cnblogs.com/Shinnosuke/p/5687685.html