<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
body {
padding: 0px;
margin: 0px;
}
div {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
}
#app2 {
top: 150px;
background-color: blue;
}
</style>
</head>
<body>
<div id="app">app1</div>
<div id="app2">app2</div>
<script>
//两种方式实现元素的拖动和添加限制条件拖动(用到了知识点原型链继承和es6继承)
//es5 原型实现
function Drag(id) {
this.oDiv = document.getElementById(id);
this.disx = 0;
this.disy = 0;
if (this.oDiv) {
this.init();
}
}
Drag.prototype.init = function() {
this.oDiv.onmousedown = function(ev) {
this.disx = ev.clientX - this.oDiv.offsetLeft;
this.disy = ev.clientY - this.oDiv.offsetTop;
document.onmousemove = this.fnmove.bind(this);
document.onmouseup = this.fnup;
return false;
}.bind(this)
}
Drag.prototype.fnmove = function(ev) {
this.oDiv.style.left = ev.clientX - this.disx + 'px';
this.oDiv.style.top = ev.clientY - this.disy + 'px';
}
Drag.prototype.fnup = function() {
document.onmousemove = null;
document.onmouseup = null;
}
new Drag('app');
function DragLimit(id) {
Drag.call(this, id);
}
DragLimit.prototype = new Drag();
DragLimit.prototype.fnmove = function(ev) {
Drag.prototype.fnmove.call(this, ev);
if (this.oDiv.offsetLeft <= 0) {
this.oDiv.style.left = '0px';
}
if (this.oDiv.offsetTop <= 0) {
this.oDiv.style.top = '0px';
}
}
new DragLimit('app2');
//es6 实现
class Drag {
constructor(id) {
this.oDiv = document.getElementById(id);
this.disx = 0;
this.disy = 0;
if (this.oDiv) {
this.init();
}
}
init() {
this.oDiv.onmousedown = function(ev) {
this.disx = ev.clientX - this.oDiv.offsetLeft;
this.disy = ev.clientY - this.oDiv.offsetTop;
document.onmousemove = this.fnmove.bind(this);
document.onmouseup = this.fnup;
return false;
}.bind(this);
}
fnmove(ev) {
this.oDiv.style.left = ev.clientX - this.disx + 'px';
this.oDiv.style.top = ev.clientY - this.disy + 'px';
}
fnup() {
document.onmousemove = null;
document.onmouseup = null;
}
}
new Drag('app');
class LimitDrag extends Drag {
fnmove(ev) {
super.fnmove(ev);
if (this.oDiv.offsetLeft <= 0) {
this.oDiv.style.left = '0px';
}
if (this.oDiv.offsetTop <= 0) {
this.oDiv.style.top = '0px';
}
}
}
new LimitDrag('app2');
</script>
</body>
</html>