我做了一个简单的jQuery,它允许我将框拖到占位符中。这工作正常,但是当我尝试对这些占位符进行排序时(甚至在将一个框拖入其中之前),它有一种奇怪的行为......
删除了原始代码,因为代码段显示了我的问题。
$(function() {
$("#dropzone").sortable({
revert: true,
opacity: 0.5
});
$("#draggable li").draggable({
connectToSortable: ".items",
helper: "clone",
revert: true,
opacity: 0.5
});
$("li.placeholder").droppable({
revert: false,
drop: function (event, ui) {
var dragging = ui.draggable.clone();
$(this).append(dragging);
}
});
$("ul, li").disableSelection();
});

body {
padding: 0;
}
.wrap {
margin-left: auto;
margin-right: auto;
width: 80%;
}
ul#draggable, ul#dropzone {
list-style-type: none;
margin: 0;
padding: 0;
}
ul#draggable li.to-drag {
background-color: #d1d1d1;
border: 2px solid #909090;
cursor: move;
float: left;
height: 100px;
margin-right: 10px;
text-align: center;
width: 100px;
}
ul#dropzone li.placeholder {
background-color: #efefef;
border: 2px dashed #c1c1c1;
cursor: move;
float: left;
height: 100px;
margin-right: 10px;
text-align: center;
width: 100px;
}
.correct {
border: 2px solid #44871f;
}
.to-drop {
background-color: #fefefe;
border: 2px solid #44871f;
}

<html>
<head>
<title>Drag & Drop</title>
<link href="style.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="drag-drop.js"></script>
</head>
<body>
<div class="wrap">
<ul id="draggable" class="items">
<li class="to-drag" class="items">
<h1>1</h1>
</li>
<li class="to-drag" class="items">
<h1>2</h1>
</li>
<li class="to-drag" class="items">
<h1>3</h1>
</li>
<li class="to-drag" class="items">
<h1>4</h1>
</li>
</ul>
<div style="height: 100px; clear: both;"></div>
<ul id="dropzone">
<li class="placeholder"></li>
<li class="placeholder"></li>
<li class="placeholder"></li>
<li class="placeholder"></li>
</ul>
</div>
</body>
</html>
&#13;
答案 0 :(得分:1)
我认为,问题在于您正在追加项目,只是不断地将它们添加到彼此之上。
首先调用.empty()
将清除上一项。
有问题的一行:
$(this).empty().append(dragging);
以上结合Jeroen的accept
行解决了这个问题:
$("li.placeholder").droppable({
revert: false,
accept: "#draggable li",
drop: function (event, ui) {
var dragging = ui.draggable.clone();
$(this).empty().append(dragging);
}
});
工作JS小提琴 - https://jsfiddle.net/csqch2g3/1/
答案 1 :(得分:1)
我认为我找到了解决方案,我已将其添加到droppable函数中:
accept: "#draggable li"