js实现框选功能?

作者站长头像
站长
· 阅读数 12

用html实现以下功能: 1,页面中间有一个1000*600的画布 2,画布上按住鼠标左键拖拽可以实现一个框选的功能 3,鼠标松开后选框消失

要求:框选用div实现,不要用canvas

回复
1个回答
avatar
test
2024-07-03

answer image

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Div Selection Demo</title>
    <style>
        #canvas {
            position: relative;
            width: 1000px;
            height: 600px;
            border: 1px solid black;
        }

        #selection-box {
            position: absolute;
            border: 2px dashed blue; /* 将边框样式改成虚线 */
            display: none;
        }
    </style>
</head>
<body>
<div id="canvas">
    <div id="selection-box"></div>
</div>
<script>
    const canvas = document.getElementById('canvas');
    const selectionBox = document.getElementById('selection-box');
    let isDragging = false;
    let startX = 0;
    let startY = 0;

    canvas.addEventListener('mousedown', e => {
        isDragging = true;
        startX = e.clientX - canvas.offsetLeft;
        startY = e.clientY - canvas.offsetTop;
        selectionBox.style.left = startX + 'px';
        selectionBox.style.top = startY + 'px';
        selectionBox.style.width = '0px';
        selectionBox.style.height = '0px';
        selectionBox.style.display = 'block';
    });

    canvas.addEventListener('mousemove', e => {
        if (isDragging) {
            const currentX = e.clientX - canvas.offsetLeft;
            const currentY = e.clientY - canvas.offsetTop;
            const width = currentX - startX;
            const height = currentY - startY;
            selectionBox.style.width = Math.abs(width) + 'px';
            selectionBox.style.height = Math.abs(height) + 'px';
            selectionBox.style.left = Math.min(currentX, startX) + 'px';
            selectionBox.style.top = Math.min(currentY, startY) + 'px';
        }
    });

    canvas.addEventListener('mouseup', e => {
        isDragging = false;
        selectionBox.style.display = 'none';
    });
</script>
</body>
</html>
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容