纯js实现DIV拖拽

写代码的时候遇到需要对绝对布局的div进行拖拽的功能,起初为了省事直接在网上扒拉了一番,看到大神张鑫旭的一篇文章《》,便直接拿来使用(膜拜大神)。但发现这段代码使用前必须设置top和left样式属性,否则拖动时div会有跳动,而且不支持多个div的拖动。于是对代码大概修改了一番,贴在这里,以备后用,希望大神勿怪。

纯js实现DIV拖拽

纯js实现DIV拖拽

1 /** 2 * 纯js实现多div拖拽 3 * @param bar, 拖拽触柄 4 * @param target, 可拖动窗口 5 * @param inWindow, 为true时只能在屏幕范围内拖拽 6 * @param callback, 拖拽时执行的回调函数。包含两个参数,target的left和top 7 * @returns {*} 8 * @private 9 */ 10 var startDrag = function(bar, target, /* optional */inWindow, /* optional */callback) { 11 (function(bar, target, callback) { 12 var D = document, 13 DB = document.body, 14 params = { 15 left: 0, 16 top: 0, 17 currentX: 0, 18 currentY: 0 19 }; 20 if(typeof bar == "string") { 21 bar = D.getElementById(bar); 22 } 23 if(typeof target == "string") { 24 target = D.getElementById(target); 25 } 26 bar.style.cursor="move"; 27 bindHandler(bar, "mousedown", function(e) { 28 e.preventDefault(); 29 params.left = target.offsetLeft; 30 params.top = target.offsetTop; 31 if(!e){ 32 e = window.event; 33 bar.onselectstart = function(){ 34 return false; 35 } 36 } 37 params.currentX = e.clientX; 38 params.currentY = e.clientY; 39 40 var stopDrag = function() { 41 removeHandler(DB, "mousemove", beginDrag); 42 removeHandler(DB, "mouseup", stopDrag); 43 }, beginDrag = function(e) { 44 var evt = e ? e: window.event, 45 nowX = evt.clientX, nowY = evt.clientY, 46 disX = nowX - params.currentX, disY = nowY - params.currentY, 47 left = parseInt(params.left) + disX, 48 top = parseInt(params.top) + disY; 49 if(inWindow) { 50 var maxTop = DB.offsetHeight - target.offsetHeight, 51 maxLeft = DB.offsetWidth - target.offsetWidth; 52 if(top < 0) top = 0; 53 if(top > maxTop) top = maxTop; 54 if(left < 0) left = 0; 55 if(left > maxLeft) left = maxLeft; 56 } 57 target.style.left = left + "px"; 58 target.style.top = top + "px"; 59 60 if (typeof callback == "function") { 61 callback(left, top); 62 } 63 }; 64 65 bindHandler(DB, "mouseup", stopDrag); 66 bindHandler(DB, "mousemove", beginDrag); 67 }); 68 69 function bindHandler(elem, type, handler) { 70 if (window.addEventListener) { 71 //false表示在冒泡阶段调用事件处理程序 72 elem.addEventListener(type, handler, false); 73 } else if (window.attachEvent) { 74 // IE浏览器 75 elem.attachEvent("on" + type, handler); 76 } 77 } 78 79 function removeHandler(elem, type, handler) { 80 // 标准浏览器 81 if (window.removeEventListener) { 82 elem.removeEventListener(type, handler, false); 83 } else if (window.detachEvent) { 84 // IE浏览器 85 elem.detachEvent("on" + type, handler); 86 } 87 } 88 89 })(bar, target, inWindow, callback); 90 };

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzzfyd.html