拖拽面向对象的写法

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

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

#div2{
  width: 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值