有一个关于div高度的问题关于鼠标移动事件的问题

我的目的是实现按住鼠标移动绘制一个div,之后还有绘制的div的拖拽,我遇到的问题是我每次在按住鼠标之后移动的时候只有在刚移动那一下才生效,之后就会卡在那块,鼠标的样式也会变成禁止的那个样式,完了放开鼠标时也没有触发mouseup事件

ps:看了一下好像是因为我是点击图片完了冒泡到外层div,这时候鼠标按住移动的话就相当于也在拖动这张图,所以鼠标会显示成禁用的样式,请问这种该怎么解决啊

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body {
            padding: 0;
            margin: 0;
        }

        #box {
            width: 100%;
            height: 100vh;
            border: 1px solid black;
            position: relative;
        }

        img {
            width: 100%;
        }

        #box div {
            border: 1px solid red;
            position: absolute;
        }
    </style>
</head>
<body>
<div id="box">
    <img src="./妮娅.jpg" alt="">
</div>
<script>
    let dom_box
    let keyType
    let state = 0 // 1:绘制 2:拖拽 3:缩放
    let dom_coordinate // 正在操作的div
    let x1, y1, divLeft, divTop
    window.onload = function (e) {
        e.preventDefault()
        dom_box = document.getElementById("box")
        dom_box.addEventListener("mousedown", mousedown)
        dom_box.addEventListener("mousemove", mousemove)
        dom_box.addEventListener("mouseup", mouseup)
        
        //鼠标按下,获取初始点
        function mousedown(e) {
            mouseState = true
            if (e.target.nodeName !== 'DIV') {
                state = 1
                x1 = e.pageX - dom_box.offsetLeft;
                y1 = e.pageY - dom_box.offsetTop;
                console.log(x1, y1)
            }
        }

        function mousemove(e) {
            let x2 = e.pageX - dom_box.offsetLeft
            let y2 = e.pageY - dom_box.offsetTop
            if (state === 1) {
                // e.target.style.cursor = 'default'
                //1.获取按下的点
                //2.创建div
                if (!dom_coordinate) {
                    dom_coordinate = document.createElement("div");
                    dom_box.appendChild(dom_coordinate);
                }
                //确定宽高
                let coordinateWidth = Math.ceil(Math.abs(x2 - x1) / 25) * 25
                let coordinateHeight = Math.ceil(Math.abs(y2 - y1) / 25) * 25
                //3.设置div的样式
                console.log(coordinateWidth)
                dom_coordinate.style.width = coordinateWidth + "px";
                dom_coordinate.style.height = coordinateHeight + "px";
                dom_coordinate.style.left = (x2 > x1 ? x1 : x1 - coordinateWidth) + "px";
                dom_coordinate.style.top = (y2 > y1 ? y1 : y1 - coordinateHeight) + "px";
            } 
        }

        function mouseup() {
            state = 0
        }
    }
</script>
</body>
</html>
阅读 1.2k
1 个回答

mousemovemouseup需要绑定在 document 上,因为在移动过程中很容易移到 div 的外面

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题