实现一个兼容性的拖拽功能

  1. div 要求position:absolute脱离文档流才能自由拖拽
    1
    2
    3
    4
    5
    6
    #div{
    width: 200px;
    height: 200px;
    background-color: red;
    position: absolute;
    }

第一步:出现问题,将事件绑定到div上面,如果移动过快,导致鼠标脱离div,到div之外,而无法移动
解决:将事件绑定到document文档上面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var a = document.getElementById('div')
a.onmousedown = function(ev) {
var oEvent = ev || event
var disX = oEvent.clientX - a.offsetLeft // 鼠标距离div边框的距离
var disY = oEvent.clientY - a.offsetTop
a.onmousemove = function(ev) {
var oEvent = ev || event
var l = oEvent.clientX - disX // div的移动距离
var t = oEvent.clientY - disY
a.style.left = l + 'px'
a.style.top = t + 'px'
}
a.onmouseup = function() {
a.onmousemove = null
a.onmouseup = null
}
}

第二步:出现问题div拖动的时候脱离可视区域,找不回div,需要对div移动做一定条件判断

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
var a = document.getElementById('div')
a.onmousedown = function(ev) {
var oEvent = ev || event
var disX = oEvent.clientX - a.offsetLeft
var disY = oEvent.clientY - a.offsetTop
document.onmousemove = function(ev) {
var oEvent = ev || event
var l = oEvent.clientX - disX
var t = oEvent.clientY - disY
// 限制在可视区域的范围之内
if(l < 0) {
l = 0
}
else if (l > document.documentElement.clientWidth - a.offsetWidth) {
l = document.documentElement.clientWidth - a.offsetWidth
};
if(t < 0) {
t = 0
}
else if (t > document.documentElement.clientHeight - a.offsetHeight) {
t = document.documentElement.clientHeight - a.offsetHeight
};
a.style.left = l + 'px'
a.style.top = t + 'px'
}
document.onmouseup = function() {
document.onmousemove = null
document.onmouseup = null
}
}

第三步:如果是老版的Firefox会出拖拽出一个图层链接
解决:阻止浏览器的默认行为,return false;
第四步:运行这段代码后我们发现,在ie浏览器里特别是ie8及之前的浏览器,当你点着有文字部分的div进行拖拽的时候,一不小心就对文字进行选中了,其他浏览器的解决办法是通过return false,而如果是ie浏览器的话,我们则要使用ie浏览器特有的一个功能:事件捕获函数setCapture和解除绑定的releaseCapture函数

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
var a = document.getElementById('div')
a.onmousedown = function(ev) {
var oEvent = ev || event
var disX = oEvent.clientX - a.offsetLeft
var disY = oEvent.clientY - a.offsetTop
if (a.setCapture) { //setCapture适用于ie6-ie8浏览器
a.onmousemove = moveArea
a.onmouseup = upArea
a.setCapture()
} else{
document.onmousemove = moveArea
document.onmouseup = upArea
}
function moveArea(ev) {
var oEvent = ev || event
var l = oEvent.clientX - disX
var t = oEvent.clientY - disY
// 不会超出可视区
if(l < 0) {
l = 0
}
else if (l > document.documentElement.clientWidth - a.offsetWidth) {
l = document.documentElement.clientWidth - a.offsetWidth
};
if(t < 0) {
t = 0
}
else if (t > document.documentElement.clientHeight - a.offsetHeight) {
t = document.documentElement.clientHeight - a.offsetHeight
};
a.style.left = l + 'px'
a.style.top = t + 'px'
}
//防止鼠标移动过快
function upArea() {
this.onmousemove = null
this.onmouseup = null
if (a.releaseCapture) {
a.releaseCapture()
};
}
return false
}
文章目录
|