|
|
这个关键是用好3个事件,一个是onmousedown一个是onmousemove一个是onmouseup
onmousedown记录当前鼠标所触发的对象,在onmousemove所触发的方法中进行移动,onmouseup放下拖动的对象。
代码:
<script language="javascript"> var checkMoving; function divMove(){ checkMoving = false; document.onmousedown=startMove; document.onmousemove=moveObj; document.onmouseup=new Function("checkMoving = false"); } function startMove(){ if(event.srcElement.className!="imgObj") return; checkMoving=true; Xdiff=event.clientX-event.srcElement.style.pixelLeft; Ydiff=event.clientY-event.srcElement.style.pixelTop; } function moveObj(){ if(!checkMoving) return true; event.srcElement.style.pixelLeft=event.clientX-Xdiff; event.srcElement.style.pixelTop=event.clientY-Ydiff; return false; }</script><body style="margin: auto;" ><div style="left:0;top:0;position:relative;overflow:hidden;width:100%;height:100%" id="div1"><img src="default.gif" style="position:relative;left:0px;top:0px;width:100px;height:100px;cursor:hand;" class=imgObj></div></body> |
|