如何实现div鼠标拖拽改变宽高

发布于:2025-07-10 ⋅ 阅读:(20) ⋅ 点赞:(0)

1. 背景

最近做了一个接口调用工具,request与response分别占用两个编辑框,如下图

入参与出参两个编辑框都是固定的,用户反馈不够灵活,希望能像postman一样可以调整宽度和高度。

2. 实现方案

可以通过鼠标拖拽来改变两个编辑框的高度和宽度,同时两个框的大小需要能联动变化,两个编辑框的高度一致,宽度总和不变。

采用拖拽手柄,

<div class="resizable-container" :style="{ height: height + 'px' }">
       <div class="resize-handle" @mousedown="startDrag"></div>
               <monaco-editor>
                </monaco-editor>
</div>

拖拽手柄样式:

/* 右下角拖拽手柄 */
.resize-handle {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 15px;
    height: 15px;
    background: #e8e8e8;
    cursor: nwse-resize;
    z-index: 100;
    border-radius: 2px 0 0 0;
}

编辑框外面的容器样式:

.resizable-container {
    width: 100%;
    // height: 650px;
    border: 1px solid #e8e8e8;
    position: relative;
    overflow: hidden;
    /* 防止内容溢出 */
    //min-width: 300px;
    /* 最小宽度限制 */
    min-height: 200px;
    /* 最小高度限制 */
}

鼠标的动作事件方法:

// 开始拖拽
    startDrag(e) {
    
      e.preventDefault();
      this.isDragging = true;
      this.startX = e.clientX;
      this.startY = e.clientY;
      this.startLeftWidth = this.leftWidth;
      this.startHeight = this.height;

      document.addEventListener('mousemove', this.handleDrag);
      document.addEventListener('mouseup', this.stopDrag);
      
      // 禁用文本选中和更改光标
      document.body.style.userSelect = 'none';
      document.body.style.cursor = 'nwse-resize';
    },
    // 处理拖拽,绑定鼠标移动监听事件
    handleDrag(e) {
      if (!this.isDragging) return;

      // 计算变化量
      const dx = e.clientX - this.startX;
      const dy = e.clientY - this.startY;

      // 调整宽度(联动变化)
      let newLeftWidth = this.startLeftWidth + dx*0.1;
      newLeftWidth = Math.max(this.minWidth, Math.min(newLeftWidth, this.maxLeftWidth));
      this.leftWidth = newLeftWidth;

      // 调整高度(同步变化)
      let newHeight = this.startHeight + dy;
      newHeight = Math.max(this.minHeight, Math.min(newHeight, this.maxHeight));
    
      this.height = newHeight;
    },
    // 停止拖拽,绑定鼠标抬起监听事件
    stopDrag() {
      this.isDragging = false;
      document.removeEventListener('mousemove', this.handleDrag);
      document.removeEventListener('mouseup', this.stopDrag);
      
      // 恢复样式
      document.body.style.userSelect = '';
      document.body.style.cursor = '';
    }

效果如下:


网站公告

今日签到

点亮在社区的每一天
去签到