JS拖动函数

JS的基本拖动函数

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
26
27
28
29
30
//HTML 结构:

<div id="box"></div>

//csc 样式:

#box{position: absolute;width: 200px;height: 200px;background: red;}

//js
window.onload = function (){
// 获取元素和初始值
var oBox = document.getElementById('box'),
disX = 0, disY = 0;
// 容器鼠标按下事件
oBox.onmousedown = function (e){
var e = e || window.event;
disX = e.clientX - this.offsetLeft;
disY = e.clientY - this.offsetTop;
document.onmousemove = function (e){
var e = e || window.event;
oBox.style.left = (e.clientX - disX) + 'px';
oBox.style.top = (e.clientY - disY) + 'px';
};
document.onmouseup = function (){
document.onmousemove = null;
document.onmouseup = null;
};
return false;
};
};