脚本文件:
function JzDrag(moveDivId, moveDivHandle) { // var me = this; this.M = false; //是否在移动对象 this.DX = { x: 0, y: 0 }; //保存起始位置和元素的位置差 this.Div = document.getElementById(moveDivId); //移动对象 this.Handle = moveDivHandle ? document.getElementById(moveDivHandle) : this.Div; //移动句柄 function GetPos(evt) { // 获取鼠标位置 evt = evt || window.event; var xPos = evt.pageX ? evt.pageX : (evt.clientX + Math.max(document.documentElement.scrollLeft, document.body.scrollLeft) - document.body.clientLeft); var yPos = evt.pageX ? evt.pageY : (evt.clientY + Math.max(document.documentElement.scrollTop, document.body.scrollTop) - document.body.clientTop); return { "x": xPos, "y": yPos }; } function LocaionSave(x, y) { // 保存临时数据 me.DX.x = parseInt(me.Div.style.left.toString().replace('px', '')) - x; me.DX.y = parseInt(me.Div.style.top.toString().replace('px', '')) - y; } function LocationSet(x, y) { // 设置移动位置 me.Div.style.left = (x + me.DX.x) + 'px'; me.Div.style.top = (y + me.DX.y) + 'px'; } function MouseDown(e) { // e.preventDefault(); me.M = true; var pos = GetPos(e); LocaionSave(pos.x, pos.y); if (me.Handle.setCapture) { me.Handle.setCapture(); } else if (window.captureEvents) { window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP); } } function MouseMove(e) { // e.preventDefault(); if (me.M == false) return; var pos = GetPos(e); LocationSet(pos.x, pos.y); } function MouseUp(e) { // e.preventDefault(); me.M = false; if (me.Handle.releaseCapture) { me.Handle.releaseCapture(); } else if (window.releaseEvents) { window.releaseEvents(Event.MOUSEMOVE | Event.MOUSEUP); } } function TouchStart(e) { // e.preventDefault(); me.M = true; var touch = e.touches[0]; LocaionSave(touch.pageX, touch.pageY); } function TouchMove(e) { // e.preventDefault(); if (me.M == false) return; var touch = e.touches[0]; LocationSet(touch.pageX, touch.pageY); } function TouchEnd(e) { // e.preventDefault(); me.M = false; } this.Handle.onmousedown = MouseDown; this.Handle.onmousemove = MouseMove; this.Handle.onmouseup = MouseUp; this.Handle.addEventListener("touchstart", TouchStart, false); //事件区分大小写 this.Handle.addEventListener("touchmove", TouchMove, false); this.Handle.addEventListener("touchend", TouchEnd, false); }
页面:
<div id="Div1" style="position:absolute;background-color:#FF4F0F; left:50px; top:60px; width:160px;height:80px;"> <h1 id="Div1m" style="line-height:30px; background-color:#f3f3f3;">拖动标题移动</h1> </div> <div id="Div2" style="position:absolute;background-color:#FF4F0F; left:150px; top:160px; width:160px;height:80px;"> 整个移动 </div>
调用:
new JzDrag('Div1', 'Div1m'); new JzDrag('Div2');