鼠标拖拽物体原理学习笔记2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
*{margin:0;padding:0;}
.main{width:500px;height:500px;border:1px solid blue;margin:100px auto;position: relative;}
.box{width:100px;height:100px;background: red;position: absolute;top:0;left:0;}
    </style>
</head>
<body>
    <div class="main">
        <div class="box"></div>
    </div>
    <script type="text/javascript">
var omain=document.querySelector('.main');
var obox=document.querySelector('.box');
var l,t;
obox.onmousedown=function (ev){
    var ev=ev||event;
    l=ev.clientX-omain.clientLeft-obox.offsetLeft;
    t=ev.clientY-obox.clientTop-obox.offsetTop;
    document.onmousemove=function (ev){
        var ev=ev||event;
        var x=ev.clientX-omain.clientLeft;
        var y=ev.clientY-omain.clientTop;
        if(x<l){
            obox.style.left=0+'px';
        }else if(x>omain.clientWidth-(obox.clientWidth-l)){
            obox.style.left=400+'px';
        }else{
            obox.style.left=x-l+'px';
        }

        if(y<t){
            obox.style.top=0+'px';
        }else if(y>omain.clientHeight-(obox.clientHeight-t)){
            obox.style.top=400+'px';
        }    
        else{
            obox.style.top=y-t+'px';
        }
        
    };
    document.onmouseup=function (){
        document.onmousemove=null;
    };

};
    </script>
</body>
</html>

鼠标拖拽效果都是在一定范围内进行的,基本原理不变,只是要花个圈圈诅咒它,让它出不来,这样它就能在里面愉快的玩耍啦

posted on 2018-02-28 20:27  李业锋  阅读(156)  评论(0)    收藏  举报

导航