拖拽原理

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>无标题文档</title>

<script src="http://457375608.github.io/liujin/javascripts/jquery-1.8.3.min.js"></script>

<style>

#div{width:300px;height:300px;background:#f00;position:absolute}

</style>

<script>

/*

 *鼠标按下

 *

 *鼠标拖动

 *

 *鼠标抬起

 * 

 */

/*window.onload=function(){

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

    oDiv.onmousedown=function(event){

        var disX=event.clientX-oDiv.offsetLeft;

        var disY=event.clientY-oDiv.offsetTop;

        document.onmousemove=function(event){

            var l=event.clientX-disX;

            var t=event.clientY-disY;

            if(l<0){

                l=0    

            }else if(l>document.documentElement.clientWidth-oDiv.offsetWidth){

                l=document.documentElement.clientWidth-oDiv.offsetWidth

            };

            if(t<0){

                t=0

            }else if(t>document.documentElement.clientHeight-oDiv.offsetHeight){

                t=document.documentElement.clientHeight-oDiv.offsetHeight

            }

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

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

        };

        document.onmouseup=function(){

            document.onmousemove=null;

            document.onmouseup=null;    

        };

        return false;    

    }    

}*/



$(function(){

    var oDiv=$("#div");

    oDiv.mousedown(function(event){

        var offset=oDiv.offset();

        var disX=event.clientX-offset.left;

        var disY=event.clientY-offset.top;

        $(document).on("mousemove",function(event){

            var l=event.clientX-disX;

            var t=event.clientY-disY;

            if(l<0){

                l=0    

            }else if(l>$(window).width()-oDiv.width()){

                l=$(window).width()-oDiv.width()

            };

            if(t<0){

                t=0    

            }else if(t>$(window).height()-oDiv.height()){

                t=$(window).height()-oDiv.height()    

            }

            //oDiv.css({left:l,top:t})    

            oDiv.offset({left:l,top:t})

        });

        $(document).mouseup(function(){

            $(document).off("mousemove mouseup")    

        });

        return false;    

    })    

})

</script>

</head>



<body>

<div id="div"></div>

</body>

</html>

 

你可能感兴趣的:(原理)