生活随笔
收集整理的這篇文章主要介紹了
自己封装的一个原生JS拖动方法。
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼:
1 function drag(t,p){
2
3 var point = p ||
null,
4 target = t ||
null,
5 resultX = 0
,
6 resultY = 0
;
7
8 (!point)? point = target : '';
//如果沒有拖動點,則拖動點默認為整個別拖動元素
9
10 function getPos(t){
11 var offsetLeft = 0
,
12 offsetTop = 0
,
13 offsetParent =
t;
14
15 while(offsetParent){
16 offsetLeft+=
offsetParent.offsetLeft;
17 offsetTop+=
offsetParent.offsetTop;
18 offsetParent =
offsetParent.offsetParent;
19 }
20
21 return {'top':offsetTop,'left'
:offsetLeft};
22 }
23
24 function core(){
25
26 var width = document.body.clientWidth ||
document.documentElement.clientWidth,
27 height = document.body.clientHeight ||
document.documentElement.clientHeight;
28 maxWidth = width -
target.offsetWidth,
29 maxHeight = height -
target.offsetHeight;
30
31 (resultX >= maxWidth)? target.style.left = maxWidth+'px' : (resultX > 0)?target.style.left = resultX +'px': '';
//重置默認位置。
32 (resultY >= maxHeight)? target.style.top = maxHeight +'px' : (resultY > 0)?target.style.top = resultY +'px':'';
//重置默認位置。
33
34 point.οnmοusedοwn=
function(e){
35 var e = e ||
window.event,
36 coordX =
e.clientX,
37 coordY =
e.clientY,
38 posX =
getPos(target).left,
39 posY =
getPos(target).top;
40
41 point.setCapture && point.setCapture();
//將Mouse事件鎖定到指定元素上。
42 document.οnmοusemοve=
function(e){
43
44 var ev = e ||
window.event,
45 moveX =
ev.clientX,
46 moveY =
ev.clientY;
47
48 resultX = moveX - (coordX - posX);
//結果值是坐標點減去被拖動元素距離瀏覽器左側的邊距
49 resultY = moveY - (coordY -
posY);
50
51 (resultX > 0 )?((resultX < maxWidth)?target.style.left = resultX+'px' : target.style.left = maxWidth+'px') : target.style.left = '0px'
;
52 (resultY > 0 )?((resultY < maxHeight)?target.style.top = resultY+'px' : target.style.top = maxHeight+'px') : target.style.top = '0px'
;
53
54 ev.stopPropagation &&
ev.stopPropagation();
55 ev.preventDefault;
56 ev.returnValue =
false;
57 ev.cancelBubble =
true;
58 };
59 };
60 document.οnmοuseup=
function(){
// 解決拖動時,當鼠標指向的DOM對象非拖動點元素時,無法觸發拖動點的onmousedown的BUG。
61 document.onmousemove =
null;
62 point.releaseCapture && point.releaseCapture();
// 將Mouse事件從指定元素上移除。
63 };
64 point.οnmοuseup=
function(e){
65 var e = e ||
window.event;
66 document.onmousemove =
null;
67 point.releaseCapture &&
point.releaseCapture();
68 };
69 }
70 core();
71 window.onresize =
core;
72 }
使用方式:
1 drag(t,p)
2 /*
3 * 說明
4 * t 表示被拖動的元素
5 * p 表示拖動點
6 */
7
8 // 注意:如果省略拖動點,默認可拖動的區域是整個被拖動元素 ?
轉載于:https://www.cnblogs.com/HCJJ/p/5834559.html
總結
以上是生活随笔為你收集整理的自己封装的一个原生JS拖动方法。的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。