标签:
拖拽是前端常用的方法之一。实现的原理是通过给鼠标的位移来改变元素的位置,其实现的过程主要分3部分:鼠标按下mousedown,鼠标移动mousemove,鼠标抬起mouseup
前期准备给元素添加绝对定位,没有绝对定位是无法实现拖拽的。
第一步:开端,首先把鼠标移到元素身上,并按下,此时发生的动作是,记录鼠标在元素身上的坐标(X,Y)X=ev.clientX-obj.offsetLeft,Y=ev.clientY-obj.offsetTop,作为后期鼠标按下并移动时作为移动的根据第二部:开始移动,当按下鼠标并移动时,鼠标坐标发生改变,鼠标在文档中移动时,元素新的坐标为(X1,Y1)X1=ev.clientX-X,Y1=ev.clientY-Y,实现元素跟随鼠标移动
第三部:停止,鼠标抬起后,移动停止,解除鼠标移动事件即可。
详细代码如下
1 function drag(obj) { 2 obj.onmousedown = function(ev) { 3 var ev = ev || event; 4 //获取鼠标按下时相对位置 5 var disX = ev.clientX - this.offsetLeft; 6 var disY = ev.clientY - this.offsetTop; 7 //设置全局捕获 8 if ( obj.setCapture ) { 9 obj.setCapture(); 10 } 11 document.onmousemove = function(ev) {
var ev = ev || event;
obj.style.left = ev.clientX - disX + ‘px‘;
obj.style.top = ev.clientY - disY + ‘px‘;
} 12 27 28 document.onmouseup = function() { 29 document.onmousemove = document.onmouseup = null; 30 //释放全局捕获 releaseCapture(); 31 if ( obj.releaseCapture ) { 32 obj.releaseCapture(); 33 } 34 } 35 36 return false; 37 38 } 39 40 }
如果想要将拖拽限制在一定的范围内则可以对(X1,Y1)进行位置判断,如拖拽范围X1>=0&&X1<=1200;Y1>=0&&Y1<=600,则上述代码可以更改为:
1 function drag(obj) { 2 obj.onmousedown = function(ev) { 3 var ev = ev || event; 4 5 var disX = ev.clientX - this.offsetLeft; 6 var disY = ev.clientY - this.offsetTop; 7 8 if ( obj.setCapture ) { 9 obj.setCapture(); 10 } 11
document.onmousemove = function(ev) {
13 var ev = ev || event;
14 //鼠标移动时获取新的坐标
15 var X1= ev.clientX - disX + ‘px‘;
16 var Y1 = ev.clientY - disY + ‘px‘;
17 if(X1<0){
18 X1=0
19 }else if(X1>1200){X1=1200}
20 if(Y1<0){
21 Y1=0
22 }else if(Y1>600){X1=600}
23 obj.style.left=X1+‘px‘
24 obj.style.top=Y1+‘px‘
25
26 }
19 20 document.onmouseup = function() {
21 document.onmousemove = document.onmouseup = null;//释放全局捕获 releaseCapture(); 23
if ( obj.releaseCapture ) {
obj.releaseCapture(); }
}
return false;
}
}
标签:
原文地址:http://www.cnblogs.com/alili/p/5486811.html