JS限制桌面拖拽

显示box在桌面拖拽,不超过浏览器边缘

JS限制桌面拖拽

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            .box{
                width: 200px;
                height: 200px;
                background-color: indianred;
                position: absolute;
            }
        </style>
    </head>
    <body>
        <div class="box"></div>
    </body>
    <script>
        var obox = document.querySelector(".box");
        obox.onmousedown=function(eve){
            var e= eve ||window.event;
            var offsetX = e.clientX -obox.offsetLeft;
            var offsetY = e.clientY - obox.offsetTop;

            document.onmousemove=function(eve){
                var e = eve || window.event;
                var l = e.clientX - offsetX;
                var t = e.clientY - offsetY;
                if(l<=0){
                    l = 0;
                }
                var clientWidth = document.documentElement.clientWidth ||document.body.clientWidth;
                if(l>=clientWidth-obox.offsetWidth){
                    l=clientWidth-obox.offsetWidth;
                }
                if(t<=0){
                    t=0;
                }
                var clientHeight = document.documentElement.clientHeight ||document.body.clientHeight;
                if(t>=clientHeight-obox.offsetHeight){
                    t=clientHeight-obox.offsetHeight;
                }
                obox.style.left =l +"px";
                obox.style.top = t+"px";
            }
        }
        document.onmouseup = function(){
            document.onmousemove = null
        }

    </script>
    </html>

JS限制桌面拖拽

上一篇:lintcode :搜索二维矩阵


下一篇:StackExchange.Redis 官方文档(二) Configuration