案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 100px;
}
.box1 {
top: 100px;
}
.box2 {
top: 300px
}
.box3 {
top: 500px
}
</style>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
</head>
<body>
<div class="box box1"></div>
<div class="box box2"></div>
<div class="box box3"></div>
</body>
<script>
$(function () {
class drag {
constructor(doc) {
this.doc = doc,
this.offsetX = 0, // 鼠标相对当前节点x的定位
this.offsetY = 0, // 鼠标相对当前节点y的定位
this.init()
}
init() {
let that = this
//第一步:鼠标点下时获取鼠标落下的位置
$(this.doc).mousedown(function (ev) {
// ev.clientX 鼠标X的位置
// $(this).offset().left 当前节点和左侧的距离
that.offsetX = ev.clientX - $(this).offset().left;
that.offsetY = ev.clientY - $(this).offset().top;
//第二步:在document下div跟随鼠标移动
$(document).mousemove(that.throttle(function (ev) {
let left = ev.clientX - that.offsetX
let top = ev.clientY - that.offsetY
$(that.doc).css({
left,
top
})
},30))
})
//第三步:在document下 鼠标抬起,取消跟随事件
$(document).mouseup(function () {
$(document).off("mousemove");
})
}
throttle(fn, delay) {
let time1 = 0
return function () {
let time2 = Date.now()
if (time2 - time1 >= delay) {
fn.apply(this, arguments)
time1 = time2
}
}
}
}
let arr = [".box1", ".box2", ".box3"]
arr.forEach(item => {
new drag(item)
})
})
</script>
</html>