在此jsFiddle中。如果更改了元素的TR,我想添加防止拖放功能。
元素只能在自己的TR中拖放。我怎么能这样做?
我应该在接受方法中添加一些限制吗?
以下是JS代码:
$(function() {
$(".dragDiv").draggable({
revert: 'invalid'
});
$(".mainTable tr td").droppable({
accept: function() {
var $this = $(this);
console.log(JSON.stringify($this.data("parent-id")+'==='+$this.parent().attr("id")));
if (($this.data("parent-id") == $this.parent().attr("id")) && $(this).find("*").length == 0)
{
return true;
}
else
{
return false;
}
},
drop: function(event, ui) {
var $this = $(this);
$this.append(ui.draggable.css({
top: 0,
left: 0
}));
ui.draggable.position({
my: "center",
at: "center",
of: $this,
using: function(pos) {
$(this).animate(pos, "slow", "linear", function() {
});
}
});
}
});
});
答案 0 :(得分:1)
按如下方式更改accept
回调:
accept: function (item) {
return $(this).closest("tr").is(item.closest("tr")) && $(this).find("*").length == 0;
}
$(function() {
$(".dragDiv").draggable({
revert: 'invalid'
});
$(".mainTable tr td").droppable({
accept: function(item) {
return $(this).closest("tr").is(item.closest("tr")) && $(this).find("*").length == 0;
},
drop: function(event, ui) {
var $this = $(this);
$this.append(ui.draggable.css({
top: 0,
left: 0
}));
ui.draggable.position({
my: "center",
at: "center",
of: $this,
using: function(pos) {
$(this).animate(pos, "slow", "linear", function() {
});
}
});
}
});
});
.mainTable {
margin: 20px auto;
padding: 0px;
}
.mainTable tr td {
width: 100px;
height: 100px;
}
.dragDiv {
text-align: center;
background-color: #00ABA9;
height: 50px;
vertical-align: middle;
margin: auto;
position: relative;
width: 50%;
}
<link href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<table border="1" class="mainTable">
<tr>
<td id="11">
<div class="dragDiv" id="1">N</div>
</td>
<td id="12"> </td>
<td id="13"> </td>
</tr>
<tr>
<td id="21"> </td>
<td id="22">
<div class="dragDiv" id="2">N</div>
</td>
<td id="23"> </td>
</tr>
<tr>
<td id="31"> </td>
<td id="32"> </td>
<td id="33">
<div class="dragDiv" id="3">N</div>
</td>
</tr>
</table>