首页 > 代码库 > Javascript:实操---拖拽(完整版)

Javascript:实操---拖拽(完整版)

CSS部分

<style type="text/css">
body{height: 3000px;
    width: 3000px;}
#div1{
    height: 100px;
    width: 100px;
    background-color: #ccc;
    position: absolute;
}
</style>

HTML部分

<div id="div1">DFDSF</div>
我发的思考附近的刷卡费的口附近的思考的撒发开急速    
</body>

 

JS部分

<script type="text/javascript">

window.onload=function (){

  var oDiv=document.getElementById("div1");

  var maxHeight=document.documentElement.clientHeight-oDiv.offsetHeight;

  var maxWidth=document.documentElement.clientWidth-oDiv.offsetWidth;

 

  oDiv.onmousedown=function (e){

    var oEvent=e||window.event;

    var disX=oEvent.clientX-oDiv.offsetLeft;

    var disY=oEvent.clientY-oDiv.offsetTop;

    

    var bodyScrollTop=document.body.scrollTop||document.documentElement.scrollTop;

    var bodyScrollLeft=document.body.scrollLeft||document.documentElement.scrollLeft;

    

    document.onmousemove=function (ev){

      var oEvent=ev||window.event;

 

      var x=oEvent.clientX-disX;

      var y=oEvent.clientY-disY;

 

      if(y<=bodyScrollTop){

        y=bodyScrollTop;

      }else if(y>=maxHeight+bodyScrollTop){

        y=bodyScrollTop+maxHeight;

      }

 

      if(x<=bodyScrollLeft){

        x=bodyScrollLeft;

      }else if(x>=bodyScrollLeft+maxWidth){

        x=bodyScrollLeft+maxWidth;

      }

      document.title=y;

 

      oDiv.style.left=x+"px";

      oDiv.style.top=y+"px";

    }

    document.onmouseup=function (){

      if(oDiv.releaseCapture){

        oDiv.releaseCapture();

      }

      document.onmousemove=null;

    }

    if(oDiv.setCapture){

     oDiv.setCapture();

    }

    return false;

  }

}

</script>