自己封装的一个原生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.onmousedown=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.onmousemove=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.onmouseup=function(){ // 解决拖动时,当鼠标指向的DOM对象非拖动点元素时,无法触发拖动点的onmousedown的BUG。 61 document.onmousemove = null; 62 point.releaseCapture && point.releaseCapture(); // 将Mouse事件从指定元素上移除。 63 }; 64 point.onmouseup=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 // 注意:如果省略拖动点,默认可拖动的区域是整个被拖动元素