原生JS实现拖动功能

Posted 卷柏的花期

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了原生JS实现拖动功能相关的知识,希望对你有一定的参考价值。

代码:

 1 function drag(id){
 2 
 3     var obj = document.getElementById(id),
 4         resultX = 0,
 5         resultY = 0;
 6 
 7     function getPos(t){
 8         var offsetLeft = 0,
 9             offsetTop = 0,
10             offsetParent = t;
11 
12         while(offsetParent){
13             offsetLeft+=offsetParent.offsetLeft;
14             offsetTop+=offsetParent.offsetTop;
15             offsetParent = offsetParent.offsetParent;
16         }
17 
18         return {‘top‘:offsetTop,‘left‘:offsetLeft};
19     }
20 
21     function core(){
22 
23         var width = document.body.clientWidth || document.documentElement.clientWidth,
24             height = document.body.clientHeight || document.documentElement.clientHeight;
25             maxWidth = width - obj.offsetWidth,
26             maxHeight = height - obj.offsetHeight;
27 
28         (resultX >= maxWidth)?  obj.style.left = maxWidth+‘px‘ :  obj.style.left = resultX +‘px‘;
29         (resultY >= maxHeight)?   obj.style.top = maxHeight +‘px‘ : obj.style.top = resultY +‘px‘;
30 
31         obj.onmousedown=function(e){
32             var e = e || window.event,
33                 coordX = e.clientX,
34                 coordY = e.clientY,
35                 posX = getPos(obj).left,
36                 posY = getPos(obj).top;
37 
38             obj.setCapture && obj.setCapture();
39             document.onmousemove=function(e){
40 
41                 var ev = e || window.event,
42                     moveX = ev.clientX,
43                     moveY = ev.clientY;
44 
45                 resultX = moveX - (coordX - posX);
46                 resultY = moveY - (coordY - posY);
47 
48                 (resultX > 0 )?((resultX < maxWidth)?obj.style.left = resultX+‘px‘ : obj.style.left = maxWidth+‘px‘) : obj.style.left = ‘0px‘; 
49                 (resultY > 0 )?((resultY < maxHeight)?obj.style.top = resultY+‘px‘ : obj.style.top = maxHeight+‘px‘) : obj.style.top = ‘0px‘; 
50 
51             };
52         };
53         document.onmouseup=function(){
54             document.onmousemove = null;
55             obj.releaseCapture && obj.releaseCapture();
56         };
57         obj.onmouseup=function(e){
58             var e = e || window.event;
59             document.onmousemove = null;
60             obj.releaseCapture && obj.releaseCapture();
61         };
62     }
63     core();
64     window.onresize = core;
65 }

使用方式:

1 drag(‘box‘);

 

以上是关于原生JS实现拖动功能的主要内容,如果未能解决你的问题,请参考以下文章

可拖动弹窗,原生js实现code

原生JS实现拖动拉开序幕特效

原生JS实现拖动拉开序幕特效

原生JS实现弹出窗口的拖拽(直接copy可用)

原生js-实现拖动模态框效果

如何使用jQuery Draggable和Droppable实现拖拽功能