Antaris与Hormress的提案

参考了CSDN“入门中……”如下文章:https://blog.csdn.net/m0_59680972/article/details/127099376
CC BY-SA 4.0

<!DOCTYPE html>
<html>
 
<head>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        div#drag {
            max-width: unset !important;
            background-image: url("https://ah-sandbox.wikidot.com/local--files/proposal/mapWF.svg");
            width: 2754px;
            height: 1598px;
            background-repeat: no-repeat;
            background-position: center center;
            background-size: 100% 100%;
             /* 给定位脱离文档流 */
            position: relative;
            top: 0;
            left: 0;
        }
    </style>
</head>
<body>
    <div id="container" style="border: solid 2px #000; width: 5000px; height: 5000px;">
        <div id="drag" style="width: 100px; height: 100px;"></drag>
    </div>
    <script>
        let box = document.getElementById("drag")
        //鼠标按下事件,鼠标移动事件 => 注意:鼠标移动的过程当中,一定是先鼠标先按下,然后才可以移动
        box.onmousedown = function(e){
            //鼠标按下,其实就是鼠标在移动前,我们要获取鼠标开始的坐标
            let startX = e.offsetX
            let startY = e.offsetY
 
            //鼠标移动过程当中
            document.onmousemove = function(e){
                //鼠标在移动的过程当中,其实就是盒子要根据鼠标移动
                //鼠标移动,我们要获取鼠标的坐标
                let endX = e.clientX
                let endY = e.clientY
 
                //求盒子移动的坐标(鼠标移动的坐标)
                let X = endX - startX;
                let Y = endY - startY;
 
                /* 拖拽的临界值判断 */
                if(X < 0){
                    X = 0;
                }
                if(Y < 0){
                    Y = 0;
                }
                if(X > document.getElementById("container").clientWidth - box.clientWidth){
 
                    X = document.getElementById("container").clientWidth - box.clientWidth
                }
                if(Y > document.getElementById("container").clientHeight - box.clientHeight){
                    Y = document.getElementById("container").clientHeight - box.clientHeight
                }
 
                //移动的过程当中,盒子的坐标变化
                box.style.top = Y + "px"
                box.style.left = X + "px"
            }            
        }
        //鼠标抬起事件,就是盒子不要移动
        document.onmouseup = function(){
            //将鼠标移动的事件清空
            document.onmousemove = null;
        }
    </script>
</body>
</html>
CC BY-SA 114514.810