jquery将可排序列表中的元素拖放到另一个列表中,仅用于分配(不移动)

问题描述 投票:0回答:1

我们有2个可排序的列表(必要的可排序),我希望能够从列表1中的元素中拖动元素而不移动列表2或列表1中的任何元素,当我删除元素时,它将返回列表1(在相同位置)并在其内部具有列表2中元素的名称。

就像分配标签过程一样。我们应该能够将相同的元素分配给其他列表中的多个元素,并且能够将列表2中的元素标记为列表1。

我不确定是否必须使用jqueryUI中的draggable或droppable脚本以及如何使用。任何想法我该怎么做?

谢谢!

var sortableOptions = {
  cursor: "move",
  placeholder: "sortable-placeholder",
  tolerance: "pointer",
  opacity: 0.8,
  scroll: true,
  scrollSensitivity: 100,
}
$('.list1').sortable(sortableOptions);
$('.list2').sortable(sortableOptions);
.list1,
.list2 {
  list-style-type: none;
  width: 40%;
  float: left;
  margin-right: 30px;
}

.list1 .item,
.list2 .item {
  border: 1px solid gray;
  padding: 10px;
}

.sortable-placeholder {
  border: 1px dotted #e6e6e6;
  height: 40px;
  color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<ul class="list1">
  <li class="item">Item 1</li>
  <li class="item">Item 2</li>
  <li class="item">Item 3</li>
</ul>

<ul class="list2">
  <li class="item">Item 4</li>
  <li class="item">Item 5</li>
  <li class="item">Item 6</li>
</ul>
javascript jquery drag-and-drop jquery-ui-sortable jquery-ui-draggable
1个回答
1
投票

好的,首先,如果您阅读jQuery可排序文档,您就会知道可排序对象获得可拖动对象的属性。

因此,初始化可排序对象时,可以设置某些属性来处理可排序事件(“开始”,“停止”,“接收”等)

var sortableOptions = {
  cursor: "move",
  placeholder: "sortable-placeholder",
  tolerance: "pointer",
  opacity: 0.8,
  scroll: true,
  connectWith: '.list1',
  helper: function(e, li) {
    copyHelper = li.clone().insertAfter(li);
    return li.clone();
  },
  stop: function() {
    copyHelper && copyHelper.remove();
  },
  receive: function(e, ui) {
    let string='<small>'+ui.item[0].innerHTML+"</small>"
    ui.item.prev().html(ui.item.prev().html()+string);
    ui.item.remove()
    copyHelper=null;
  },
  scrollSensitivity: 100,
}

请注意connectWith选项 - 它确保您的列表已连接。我准备了一个应该重现预期行为的小提琴:

JSFiddle

警告:当前代码不会检查重复项,因此,如果您将item1从list1传递到list2并再次传回,​​那么您将在list1中将item1作为重复项!

编辑

我已经改变了小提琴和代码片段来反映你的问题,Here

请注意,如果您不断更改列表中的项目,它们将越来越大。我没有纠正,因为这可能是你期望的行为。

我懂了

好的,现在你已经要求让我摸不着头脑的东西:P

所以,我的解决方案是:

将CSS更改为:

.list1,
.list2 {
  list-style-type: none;
  width: 40%;
  float: left;
  margin-right: 30px;
}

.list1 .item,
.list2 .item {
  float: left; //THIS ONE IS THE IMPORTANT ONE
  border: 1px solid gray;
  padding: 10px;
}

.sortable-placeholder {
  border: 1px dotted #e6e6e6;
  height: 40px;
  color: #fff;
}

这将使您的列表处于水平状态(非常明显地表示您要添加的元素)。

但是,如果您希望更改为垂直列表,我的建议是停止使用可滚动,除非您确实需要。根据我的研究,scrollable将始终为新元素创建“空间”,因此要么:

  • 改变jquery库(imo,似乎是一个坏主意),
  • 您将新的事件侦听器(mouseup / mousedown / mousemove)添加到每个列表元素。
  • 或者你放弃了可滚动和“硬编码”你需要的行为。

JSFiddle

© www.soinside.com 2019 - 2024. All rights reserved.