鼠标拖拽的简单实现

这篇文章介绍一个最基础的方式来实现鼠标拖拽。

思路

  • 如果实现拖拽?通过计算鼠标的移动距离,来设定被拖拽对象的移动距离,以达到拖拽的效果。
  • 如果确定何时拖拽?通过设置一个flag、并配合鼠标的事件绑定来完成。

HTML 和 CSS 设置

首先设置一个 divid = 'box' 方便获取;其次设置 position: relative; 这样才能使 style.top 起作用。

具体代码:

1
2
3
4
5
6
7
8
9
10
<div id="box" class="box">
</div>
<style>
.box {
width: 300px;
height: 300px;
background: #eeeeee;
position: relative;
}
</style>

JS 实现

首先定义一个 Drag 的原型

  • this.ele 是拖拽对象
  • this.mouse 是鼠标的坐标
  • this.current 是拖拽的原始坐标
  • this.start 是开始的 flag
1
2
3
4
5
6
7
8
9
10
11
12
function Drag(ele) {
this.ele = ele
this.mouse = {
x: 0,
y: 0
}
this.current = {
x: this.ele.offsetLeft,
y: this.ele.offsetTop
}
this.start = false
}

在定义开始拖拽的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Drag.prototype = {
init: function (e) {
console.log(this, e)
e = e || window.event
this.mouse = {
x: e.clientX,
y: e.clientY
}
this.current = {
x: this.ele.offsetLeft,
y: this.ele.offsetTop
}
this.start = true
},
move: function (e) {
if (this.start) {
e = e || window.event
this.ele.style.left = this.current.x + (e.clientX - this.mouse.x) + 'px'
this.ele.style.top = this.current.y + (e.clientY - this.mouse.y) + 'px'
}
},
up: function () {
this.start = false
}
}

调用方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var box = document.getElementById('box')
var drag = new Drag(box)
var dragEvent = {
addListen: function (ele, drag) {
ele.onmousedown = drag.init.bind(drag)
ele.onmousemove = drag.move.bind(drag)
ele.onmouseup = drag.up.bind(drag)
},
deleteListen: function (ele) {
ele.onmousedown = null
ele.onmousemove = null
ele.onmouseup = null
}
}
dragEvent.addListen(box, drag)