这个关键是用好3个事件,一个是onmousedown一个是onmousemove一个是onmouseup
onmousedown记录当前鼠标所触发的对象,在onmousemove所触发的方法中进行移动,onmouseup放下拖动的对象。我完成过这样的功能,但是代码牵涉到其他功能所以不好提取出来。说简单点就是obj跟随鼠标移动的过程
关键代码:
document.onmousemove = MouseMove;
function MouseMove(){
if(Drag){
document.onmousemove = new Function();
tdObj.style.top = (event.clientY- tdObj.mouseDownY);
tdObj.style.left = (event.clientX- tdObj.mouseDownX);
document.onmousemove = MouseMove;
}
//....其他省略了
}

解决方案 »

  1.   

    <body style="margin: auto;" onLoad="divMove();">
    <div style="left:0;top:0;position:relative;overflow:hidden;width:100%;height:100%" id="div1">
    <img src="img.jpg" style="position:relative;left:0px;top:0px;width:100px;height:100px;cursor:hand;" class=imgObj>
    </div>
    </body>
    <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>