HTML:
<div class="character_list">
<div id="draggable" class="character_list_container">
<div><img class="1" src="http://ahna.web44.net//img/charas/13.png" /></div>
<div><img class="2" src="http://ahna.web44.net//img/charas/13.png" /></div>
<div><img class="3" src="http://ahna.web44.net//img/charas/13.png" /></div>
<div><img class="4" src="http://ahna.web44.net//img/charas/13.png" /></div>
<div><img class="5" src="http://ahna.web44.net//img/charas/13.png" /></div>
<div><img class="6" src="http://ahna.web44.net//img/charas/13.png" /></div>
</div>
<div id="droppable_slots" class="current_team">
<div id="slot" class="1">1</div>
<div id="slot" class="2">2</div>
<div id="slot" class="3">3</div>
</div>
</div>
jQuery的:
$(function() {
$("#draggable>div>img").draggable({
start: function(){
$(this).css({display: 'none'});
},
stop: function(){
$(this).css({display: 'block'});
},
revert: function(dropped) {
var dropped = dropped && dropped[0].id== "slot";
if(!dropped) {
$(this).appendTo($(this).data('originalParent'))
}
return !dropped;
},
helper: function() { return $(this).clone().appendTo('body').show(); },
containment: '.sel_screen_left'
}).each(function() {
$(this).data('originalParent', $(this).parent())
});
$("#droppable_slots>div").droppable({
drop: function(event, ui) {
var $this = $(this);
var content = $.trim($this.html()).length;
if(content > 0) {
$this.html("");
}
$this.append(ui.draggable);
var width = $this.width();
var height = $this.height();
var cntrLeft = (width / 2) - (ui.draggable.width() / 2);
var cntrTop = (height / 2) - (ui.draggable.height() / 2);
ui.draggable.css({
left: cntrLeft + "px",
top: cntrTop + "px"
});
}
});
});
实例:http://jsfiddle.net/CVbzg/3/
正如您在jsfiddle示例中所看到的,当图像被删除时,它会完全锁定,但是当您移出放置区域时,它会丢失可拖动性而不是恢复并附加到其原始父级。
有人可以帮忙吗?
答案 0 :(得分:2)
当你将droppable放入drop target后稍微移动它并且它失去了可拖动性,这是因为
$this.html("");
在放置处理程序中,draggable仍在放置目标内。擦除放置目标的HTML时,还会删除应该重新附加的元素。这会返回一个语法错误,因为该元素不再存在,从而中断了克隆的操作,并且可擦除了可拖动的文件。
这是一个快速修复:
drop: function(event, ui) {
var $this = $(this);
if ($this.find('.ui-draggable').length) return; //don't overwrite occupied spot
$this.empty(); //empty() sounds more semantic than html('') for me, it does the same thing =]
$this.append(ui.draggable);
//...
}
它不允许用另一个元素覆盖放置目标内的被删除元素,其中包括在自己的放置目标上重新删除元素。
另一种解决方案是将已经删除的可拖动区域移回其起始位置,然后再添加可拖动的拖拽:
drop: function(event, ui) {
var $this = $(this),
containsDropped = $this.find('.ui-draggable');
if (containsDropped.length) containsDropped.appendTo(containsDropped.data('originalParent'));
$this.empty();
你必须小心不要无意中删除可拖动的。 =]