思路:
1.拖动div的position须为absolute,因为它不遵循html默认的flow
2.拖动事件包括(点住鼠标-->移动鼠标-->释放鼠标)
3.拖动div的位移量就是点住鼠标时的鼠标坐标(x,y)-释放鼠标时的鼠标坐标(x,y)。所以需要监听onmousedown和onmouseup事件。
代码:
<html> <head> <title>DragDiv</title> <mce:script type="text/javascript" src="drag.js" mce_src="drag.js"></mce:script> <mce:script type="text/javascript"><!-- window.onload = function() { window.document.onmousedown = function(e){ startDrag(e); }; window.document.onmouseup = function(e) { overDrag(e); }; }; // --></mce:script> </head> <body> <div id="dragobj1" style="width:20%;height:60px;background-color:green;position:absolute;left:30px;top:40px;cursor:hand;"> </div> <div id="dragobj2" style="width:20%;height:60px;background-color:red;position:absolute;left:70px;top:90px;cursor:hand;"> </div> </body> </html>
/** *@author:bruce bao *功能:拖拽DOM ELEMENT对象,@version1 */ /** *全局变量: *oldMouseX:鼠标在事件触发时的X坐标,初始化为0 *oldMouseY:鼠标在事件触发时的Y坐标,初始化为0 *dragObjStatus:是否执行拖拽动作的flag,初始化为0,0-不执行,1-执行 *dragObj:拖拽的DOM ELEMENT,初始化为null */ var oldMouseX = 0; var oldMouseY = 0; var dragObjStatus = 0; var dragObj = null; /** *初始化拖拽的全局变量 */ function startDrag(e) { var eve = window.event || e; //得到触发事件的源对象,也就是要拖拽的对象 if(!eve.target) { eve.target = eve.srcElement; } //如果事件的源对象不是body,初始化全局变量,为拖拽做好准备,否则就还原全局变量为默认值 if(eve.target.tagName.toLowerCase() != 'body') { oldMouseX = eve.clientX; oldMouseY = eve.clientY; dragObjStatus = 1; dragObj = eve.target; } else { oldMouseX = 0; oldMouseY = 0; dragObjStatus = 0; dragObj = null; } } /** *完成拖拽 */ function overDrag(e) { var eve = window.event || e; if(dragObjStatus == 1) { var newMouseX = eve.clientX; var newMouseY = eve.clientY; if(dragObj) { //拖拽对象的初始X坐标 var objX = parseInt(dragObj.style.left); //拖拽对象的初始Y坐标 var objY = parseInt(dragObj.style.top); //拖拽对象拖拽后的X,Y坐标 dragObj.style.left = (objX + (newMouseX - oldMouseX)) + "px"; dragObj.style.top = (objY + (newMouseY - oldMouseY)) + "px"; } //还原全局变量为默认值 oldMouseX = 0; oldMouseY = 0; dragObjStatus = 0; dragObj = null; } }