拖拽效果

发布于 2020-08-09  188 次阅读 本文共1144个字


demo源码如下,这里只实现了简单的拖拽,还有更多的碰撞检测之类的后续再接着补充哦~

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>简单的拖拽</title>
    <link rel="stylesheet" href="../toolkit/reset.min.css">
    <style>
        #box{
            height: 200px;
            width: 200px;
            background-color: #e277ff;
            position: absolute;
            cursor: move;
            right: 10px;
        }
    </style>
</head>
<body>
<div id="box"></div>
<script>
    var box=document.getElementById("box");
    function drag(e) {
        e=e||window.event;
        var _this=this;
        var mouseX=e.clientX,
                mouseY=e.clientY,
                boxL=this.offsetLeft,
                boxT=this.offsetTop;
        document.onmousemove=function (e) {
            e=e||window.event;
            var curMouseX=e.clientX,
                    curMouseY=e.clientY,
                    curBoxL=curMouseX-mouseX+boxL,
                    curBoxT=curMouseY-mouseY+boxT;

            var minW=0,maxW=((document.documentElement.clientWidth||document.body.clientWidth)-_this.offsetWidth);
            var minH=0,maxH=((document.documentElement.clientHeight||document.body.clientHeight)-_this.offsetHeight);
            if(curBoxL<=minW){
                curBoxL=minW;
            }else if(curBoxL>=maxW){
                curBoxL=maxW
            }
            if(curBoxT<=minH){
                curBoxT=minH;
            }else if(curBoxT>=maxH){
                curBoxT=maxH;
            }

            _this.style.left=curBoxL+"px";
            _this.style.top=curBoxT+"px";
        };
        document.onmouseup=function () {
            document.onmousemove=null;
        }
    }
    box.onmousedown=drag;
</script>
</body>
</html>

努力,只为遇见更好的自己!