面向对象的拖拽

面向对象的拖拽

实现一个div#one在浏览器区域自由拖拽,另外一个div#two有浏览器的边界限定

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
  //给两个div设置样式
    #one {
      width:100px;
      height:100px;
      background-color: red;
      position:absolute;
    }
    #two {
      width:100px;
      height:100px;
      background-color: lightblue;
      position:absolute;
      right:0;
    }
  </style>
  //js外链
  <script src="./drag.js"></script>
  <script>
    window.onload = function(){
      var box1 = new Drag('one');
      box1.init()
      var box2 = new Frag('two');
      box2.init()
    }
  </script>
</head>
<body>
  <div id="one"></div>
  <div id="two"></div>
</body>
</html>

drag.js

//父类 构造函数Drag
function Drag(id){
  this.box = document.getElementById(id);
  this.selfL = 0;
  this.selfT = 0;
}
Drag.prototype.init=function(){
  var _this = this;
  this.box.onmousedown = function(ev){
_this.down(ev);
  }
}
//box.onmousedown
Drag.prototype.down = function(ev){
  var _this = this;
  this.selfL = ev.offsetX;
  this.selfT = ev.offsetY;
  document.onmousemove = function(ev){
    _this.move(ev);
  }
  document.onmouseup = function(){
    _this.up();
  }
}
//document.onmousemove
Drag.prototype.move = function(ev){
  var l = ev.clientX - this.selfL;
  var t  = ev.clientY - this.selfT;
  this.box.style.left = l + 'px';
  this.box.style.top = t + 'px';
}
//document.onmouseup
Drag.prototype.up = function(){
  document.onmousemove = null;
  document.onmouseup = null;
}
//子类 构造函数Frag
function Frag(id){
  // 对象冒充继承,继承父类构造函数中的公有属性和方法
  Drag.call(this, id);
}
inherit(Drag, Frag)
function inherit(Parent, Child){
  // 寄生式继承,继承父类原型对象中共享的属性和方法
  function Super(){};
  Super.prototype = Parent.prototype;
  Child.prototype = new Super();
  Child.prototype.constructor = Child;
}
//重构move方法
Frag.prototype.move = function(ev){
  var l = ev.clientX - this.selfL;
  var t  = ev.clientY - this.selfT;
  //边界限定
  if(l <= 0){
    l = 0;
  }else if(l >= document.documentElement.clientWidth - this.box.offsetWidth){
    l = document.documentElement.clientWidth - this.box.offsetWidth
  }
  if(t <= 0){
    t = 0;
  }else if(t >= document.documentElement.clientHeight - this.box.offsetHeiclientHeight){
    t = document.documentElement.clientHeight - this.box.offsetHeight;
  }
  this.box.style.left = l + 'px';
  this.box.style.top = t + 'px';
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值