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

如何在droppable容器中释放元素时让其定位在精确释放位置?

Fixing Precise Positioning for Drag-and-Drop Clone Elements

Hey there! Let's get that drag-and-drop positioning sorted out. From the code snippet you shared, I can see two key issues throwing off the precise placement:

  • You're using the drag event in your .droppable setup, which isn't meant for handling when an element is released—we need the drop event instead.
  • You aren't calculating the correct offset between the mouse, the cloned element, and the drop container, which leads to misalignment.

Here's the corrected code with explanations:

$(".draggable_image").draggable({
  helper: 'clone',
  // Track the mouse's offset relative to the clone when dragging starts
  start: function(event, ui) {
    ui.helper.data('mouseOffset', {
      left: event.pageX - ui.helper.offset().left,
      top: event.pageY - ui.helper.offset().top
    });
  }
});

$(".droppable").droppable({
  accept: ".draggable_image",
  // Handle the element being dropped here
  drop: function(event, ui) {
    const $dropContainer = $(this);
    const mouseOffset = ui.helper.data('mouseOffset');

    // Calculate the exact position of the clone inside the drop container
    const relativeX = event.pageX - $dropContainer.offset().left - mouseOffset.left;
    const relativeY = event.pageY - $dropContainer.offset().top - mouseOffset.top;

    // Create the clone, position it, and add it to the container
    const $finalClone = ui.helper.clone();
    $finalClone.css({
      position: 'absolute',
      left: `${relativeX}px`,
      top: `${relativeY}px`
    }).removeClass('draggable_image') // Optional: remove original draggable class if needed
      .appendTo($dropContainer);

    // Optional: Make the cloned element draggable too
    $finalClone.draggable();
  }
});

Critical Notes to Make This Work:

  • Set .droppable to relative positioning: Add this CSS rule to your stylesheet:
    .droppable {
      position: relative;
    }
    
    This ensures the absolute-positioned clone is placed relative to the drop container, not the entire page.
  • Mouse offset tracking: By saving the distance between the mouse cursor and the clone's top-left corner when dragging starts, we guarantee the clone stays exactly where you release it relative to your mouse.
  • Use the drop event: This is the dedicated event in jQuery UI's droppable for handling when a draggable element is released over the container—drag fires continuously while dragging, which isn't what we need here.

That should fix the positioning issue and let your cloned elements land exactly where you drop them!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:27:12