<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="drag.css">
</head>
<body>
<div id="div1">div1</div>
<div id="div2">div2</div>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/javascript">
class Drag {
constructor(id) {
this.oDiv = document.querySelector(id);
this.disX = 0;
this.disY = 0;
this.init();
}
init() {
console.log(this)
console.log(this.oDiv)
this.oDiv.onmousedown = function(ev) {
console.log('onmousedown')
// 点击时鼠标位置到div边缘的距离
this.disX = ev.clientX - this.oDiv.offsetLeft;
this.disY = ev.clientY - this.oDiv.offsetTop;
document.onmousemove = this.fnMove.bind(this);
document.onmouseup = this.fnUp.bind(this);
// 阻止默认文字选中
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('#div1')
// limitDrag继承drag的拖拽功能,限制拖拽区域
class limitDrag extends Drag {
fnMove(ev) {
super.fnMove(ev);
// 限制范围
if(this.oDiv.offsetLeft < 0) {
this.oDiv.style.left = 0;
}
if(this.oDiv.offsetTop < 0) {
this.oDiv.style.top = 0;
}
}
}
new limitDrag('#div2')
</script>
</body>
</html>