问题
Is there any configurable option to achieve the feature like replacing the list items rather than swapping items in JQuery Sortable UI. Current feature is like Item1 Swaps with Item2 and vice versa. I need a feature like, If item2 is dragged and dropped on Item1, item2 should replace Item1 and Item2 position will be empty. Any help? thanks.
回答1:
You can do it with the following code:
$('#container').sortable({
connectWith: '#container',
items: '.children', //#container > .children
cursor: 'move',
receive: function(event, ui) {
var item = $(ui.item);
var sender = $(ui.sender);
sender.append(item.siblings('.children'));
}
});
回答2:
Hiya demo http://jsfiddle.net/CZm9C/2/
Now drag from first box to the second. Hope this helps and please let me know if I missed anything, :)
Jquery
$(document).ready(function(){
$(".leftDiv .item").draggable({
helper: function(ev, ui) {
return "<span class='helperPick'>"+$(this).html()+"</span>";
},
connectToSortable: ".rightDiv"
});
$(".rightDiv").sortable({
'items': ".item",
'receive': function(event, ui){
// find the class of the dropped ui, look for the one with the integer suffix.
var clazz = getClassNameWithNumberSuffix(ui.item);
$('.leftDiv .' + clazz).draggable( "option", "revert", true )
if($('.rightDiv .' + clazz).length > 1){
$('.rightDiv .' + clazz + ':not(:first)').remove();
}
$('.leftDiv .' + clazz).remove();
}
});
});
function getClassNameWithNumberSuffix(el) {
var className = null;
var regexp = /\w+\d+/;
$($(el).attr('class').split(' ')).each(function() {
if (regexp.test(this)) {
className = this;
return false;
}
});
return className;
}
HTML
<div class="leftDiv"> drag to ==>
<div class="item item1">Item 1</div>
<div class="item item2">Item 2</div>
<div class="item item3">Item 3</div>
<div class="item item4">Item 4</div>
<div class="item item5">Item 5</div>
<div class="item item6">Item 6</div>
</div>
<div class="rightDiv"> ==> To this
<div class="item item1">Item 1</div>
<div class="item item2">Item 2</div>
<div class="item item3">Item 3</div>
<div class="item item4">Item 4</div>
<div class="item item5">Item 5</div>
<div class="item item6">Item 6</div>
</div>
CSS
.leftDiv, .rightDiv {width:120px; float:left; border:1px solid #000; padding:5px; margin:10px; min-height:130px}
.rightDiv {margin-left:40px}
.item {height:20px; line-height:20px; text-align:center; border:1px solid #EEE; background-color:#FFF}
.helperPick {border:1px dashed red; height:20px; line-height:20px; text-align:center; width:120px}
来源:https://stackoverflow.com/questions/10290510/jquery-sortable-replacing-items-rather-than-swapping-items