1.es6 class的使用
之前在Jquery時代,實現拖拽功能都是使用函數直接搞,有了es6中的class,可以很好的封裝相關的功能,只要給個ID就可以,想拖誰就拖誰!不過步驟還是老一套。
- 先在拖拽元素DOM上添加onmousedown事件,獲取鼠標點擊位置,並添加document的onmousemove事件和onmouseup事件
- 只要鼠標不彈起,就會執行onmousemove事件,然後事件中給拖拽元素top,left賦值,不想讓他出去可以,限制範圍
- 鼠標彈起時,移除事件
js真是有點Java的樣子啦!
<!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>