拖拽实现步骤:
鼠标按下 开始拖拽
鼠标移动 拖拽过程
鼠标松开 结束
然后在移动过程中,将偏移值赋值给拖拽的对象
var params = { left: 0, top: 0, currentX: 0, //开始时的x坐标 currentY: 0, //开始时的y坐标 flag: false //标记鼠标按下或松开 }; //获取相关CSS属性 //o是移动对象 var getCss = function (o, key) { //兼容ie的currentStyle和其他浏览器支持的getComputedStyle方法 return o.currentStyle ? o.currentStyle[key] : document.defaultView.getComputedStyle(o, false)[key]; }; //拖拽的实现 var startDrag = function (bar, target, callback) { if (getCss(target, "left") !== "auto") { params.left = getCss(target, "left"); } if (getCss(target, "top") !== "auto") { params.top = getCss(target, "top"); } //触发拖拽的对象发生鼠标按下事件 bar.onmousedown = function (event) { params.flag = true; //兼容ie if (!event) { event = window.event; //防止IE文字选中 bar.onselectstart = function () { return false; } } var e = event; //传入初始坐标 params.currentX = e.clientX; params.currentY = e.clientY; }; document.onmouseup = function () { params.flag = false; if (getCss(target, "left") !== "auto") { //获取移动后的x params.left = getCss(target, "left"); } if (getCss(target, "top") !== "auto") { //获取移动后的y params.top = getCss(target, "top"); } }; document.onmousemove = function (event) { var e = event ? event : window.event; //鼠标还在按下状态 if (params.flag) { //获取现在的坐标 var nowX = e.clientX, nowY = e.clientY; //鼠标移动路径 var disX = nowX, disY = nowY; //将移动后的坐标传给target target.style.left = disX + "px"; target.style.top = disY + "px"; if (event.preventDefault) { event.preventDefault(); } return false; } if (typeof callback == "function") { callback(parseInt(params.left) + disX, parseInt(params.top) + disY); } } };