es6 class的使用
之前在Jquery时代,实现拖拽功能都是使用函数直接搞,有了es6中的class,可以很好的封装相关的功能,只要给个ID就可以,想拖谁就拖谁!不过步骤还是老一套。
- 先在拖拽元素DOM上添加onmousedown事件,获取鼠标点击位置,并添加document的onmousemove事件和onmouseup事件
- 只要鼠标不弹起,就会执行onmousemove事件,然后事件中给拖拽元素top,left赋值,不想让他出去可以,限制范围
- 鼠标弹起时,移除事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box" id="box"></div>
<script type="text/javascript">
class Drag {
constructor(id) {
this.oDiv = document.querySelector(id);
this.disX = 0;
this.disY = 0;
this.init();
}
init() {
this.oDiv.onmousedown = function (e) {
//阻止内容被选中
e.preventDefault();
this.disX = e.clientX - this.oDiv.offsetLeft;
this.disY = e.clientY - this.oDiv.offsetTop;
document.onmousemove = this.fnMove.bind(this);
document.onmouseup = this.fnUp.bind(this);
}.bind(this);
}
//确保范围不会超出
ensureRange(e){
let left = e.clientX - this.disX;
let width = window.innerWidth - this.oDiv.offsetWidth;
if (left < 0) {
left = 0;
} else if (left > width) {
left = width;
}
let top = e.clientY - this.disY;
let height = window.innerHeight - this.oDiv.offsetHeight;
if (top < 0) {
top = 0;
} else if (top > height) {
top = height;
}
return {
top,
left
}
}
fnMove(e) {
let xy = this.ensureRange(e);
this.oDiv.style.left = xy.left + "px";
this.oDiv.style.top = xy.top + "px";
}
//弹起清除
fnUp() {
document.onmousemove = null;
document.onmouseup = null;
}
}
new Drag("#box");
</script>
</body>
</html>