拖拽

216 阅读1分钟
    * {
        margin: 0;
        padding: 0;
    }

    #box {
        width: 200px;
        height: 200px;
        background: cornflowerblue;
        position: absolute;
        left: 100px;
        top: 0;
    }
</style>
</head>

<body>
<div id="box"></div>
<script>
    let box = document.getElementById('box');

    box.onmousedown = function (e) {
        let offsetLeft = box.offsetLeft;
        let offsetTop = box.offsetTop;
        let oEvent = e || event;
        /* 获取鼠标在盒子内部的x,y的距离 */
        let neibuX = oEvent.clientX - offsetLeft;
        let neibuY = oEvent.clientY - offsetTop;
       
        box.onmousemove = function (e) {
            let oEventMove = e || event;
            let left = oEventMove.clientX - neibuX;
            let top = oEventMove.clientY - neibuY;
            /* document.documentElement.clientWidth文档可视区域的宽度 */
            let maxW = document.documentElement.clientWidth - box.offsetWidth;
            let maxH = document.documentElement.clientHeight - box.offsetHeight;
            /* 这个是保证不能为负数,超出左和上边界 */
            if(left<0) left = 0;
            if(top<0) top = 0;
            /* /* 这个是保证不能超出右和下边界 */ 
            if(left>maxW) left = maxW;
            if(top>maxH) top = maxH;

            box.style.left = left + 'px' ;
            box.style.top = top + 'px' ;
        }
    }
    box.onmouseup = function(){
        box.onmousemove = null;
    }
</script>
</body>