jQueryUI:如何将可放置区域限制为多个 div?

jQueryUI: how to restrict droppable area to multiple divs?

感觉问题已经回答了:

我有 3 个时间轴和一些可拖动的元素要放在那里。出于某种原因,我无法让它工作。这是我使用的语法:containment: ".timeline1, .timeline2, .timeline3"

$(function() {
  $(".timeline1, .timeline2, .timeline3").droppable();

  $(".event").draggable({
    containment: ".timeline1, .timeline2, .timeline3"
  });
});
.timeline1, .timeline2, .timeline3 {
  width: 500px;
  height: 40px;
  border: 3px dashed gray;
  margin-bottom: 10px;
}
.event {
  height: 40px;
  background: gray;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />

<div class="timeline1"></div>
<div class="timeline2"></div>
<div class="timeline3"></div>

<div class="event">dance</div>
<div class="event">sleep</div>
<div class="event">eat</div>


在文档中找到更新:http://api.jqueryui.com/draggable/#option-containment

The draggable element will be contained to the bounding box of the first element found by the selector

问题仍然有效,我很想知道如何将可放置区域限制为多个 div?

我不确定您是否可以使用包含选项来执行此操作,但您可以使用 snap、snapMode 和 revert 来完成您正在尝试执行的操作。

我会在您的时间轴元素中添加一个常见的 class,例如 timeline-droppable,以使其更容易:

<div class="timeline1 timeline-droppable"></div>
<div class="timeline2 timeline-droppable"></div>
<div class="timeline3 timeline-droppable"></div>

使用捕捉选项捕捉到您的可放置时间轴。使用 revert 选项确定 draggable 是否被放置在有效的 droppable 中:

$(function() {
    $(".timeline-droppable").droppable();

    $(".event").draggable({
        snap: ".timeline-droppable",
        snapMode: "inner",
        revert:  function(droppedElement) {
            var validDrop = droppedElement && droppedElement.hasClass("timeline-droppable");
            return !validDrop;
        } 
    });
});

当然,您需要调整 CSS 以使您的事件元素很好地适合您的时间线元素。