面向对象的拖拽
实现一个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';
}