You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现不同形状Div的拖拽投放及容器内无重叠拖拽功能

实现可拖拽形状到容器且内部元素不重叠的方案

我来帮你完成这个需求,下面是完整的实现代码,包含拖拽克隆元素到指定容器、容器内元素可自由拖拽、元素间不重叠这三个核心功能:

HTML 结构

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>

<div class="square">正方形</div>
<div class="rect">长方形</div>
<div id="canvas">投放容器</div>

CSS 样式

#canvas {
  height: 300px;
  border: 1px solid lightgrey;
  margin-top: 20px;
  position: relative; /* 为内部绝对定位的元素提供参照 */
}

.square, .rect {
  display: inline-block;
  height: 50px;
  border: 1px solid lightblue;
  text-align: center;
  line-height: 50px; /* 让文字垂直居中 */
  cursor: move; /* 提示可拖拽 */
}

.square {
  background-color: lightyellow;
  width: 80px;
}

.rect {
  background-color: lightgreen;
  width: 120px; /* 区分长方形和正方形 */
}

.canvas-item {
  position: absolute; /* 让容器内的元素可以自由定位 */
}

JavaScript 逻辑

// 初始化外部形状的拖拽(克隆模式)
$(".square, .rect").draggable({
  helper: 'clone',
  cursor: 'move'
});

// 初始化投放容器
$("#canvas").droppable({
  accept: ".rect, .square",
  drop: function(ev, ui) {
    // 克隆拖拽元素并添加到容器中
    const clonedItem = $(ui.draggable).clone()
      .addClass('canvas-item')
      .appendTo(this);
    
    // 初始化容器内元素的拖拽,限制在容器内,且防止重叠
    clonedItem.draggable({
      containment: "#canvas",
      cursor: 'move',
      // 拖拽过程中检测碰撞
      drag: function(event, ui) {
        // 遍历容器内其他元素,检查是否重叠
        $("#canvas .canvas-item").not($(this)).each(function() {
          const target = $(this);
          // 获取当前拖拽元素和目标元素的位置信息
          const uiPos = ui.position;
          const targetPos = target.position();
          const uiWidth = $(this).outerWidth();
          const uiHeight = $(this).outerHeight();
          const targetWidth = target.outerWidth();
          const targetHeight = target.outerHeight();
          
          // 检测是否发生重叠
          const overlap = !(
            uiPos.left + uiWidth < targetPos.left ||
            uiPos.left > targetPos.left + targetWidth ||
            uiPos.top + uiHeight < targetPos.top ||
            uiPos.top > targetPos.top + targetHeight
          );
          
          if (overlap) {
            // 若重叠,取消当前拖拽动作
            ui.position = ui.originalPosition;
          }
        });
      }
    });
    
    // 设置克隆元素的初始位置为投放点(居中对齐鼠标)
    clonedItem.css({
      left: ev.pageX - $(this).offset().left - clonedItem.outerWidth()/2,
      top: ev.pageY - $(this).offset().top - clonedItem.outerHeight()/2
    });
  }
});

关键功能说明

  • 外部元素拖拽克隆:通过helper: 'clone'实现拖拽时克隆元素,原元素保留在原位
  • 容器内拖拽限制:给容器内的元素设置containment: "#canvas",确保拖拽范围不会超出容器边界
  • 防重叠逻辑:在drag事件中遍历容器内其他元素,通过坐标计算判断是否重叠,若重叠则重置拖拽位置到初始状态
  • 定位处理:给容器内的元素添加position: absolute,配合容器的position: relative,实现元素在容器内的自由定位

内容的提问来源于stack exchange,提问作者Divyesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:29:07