jQuery snippet to swap two sets of elements with animation
is there some jQuery code to swap 2 sets of elements with animation开发者_开发知识库?
i only found Move list item to top of unordered list using jQuery but its too limited (only slide element to top and not accounting for different margins).
see this fiddle. arbitrary borders, margins, paddings, sizes etc. supported and still no jumps at animation end.
function slideSwap($set1, $set2) {
//$elem.append(infoString($elem));
//$after.append(infoString($after));
$set1.css("color", "red");
$set2.css("color", "blue");
var $set3 = $set2.last().nextAll();
$set3.css("color", "green");
var mb_prev = cssprop($set1.first().prev(), "margin-bottom");
if (isNaN(mb_prev)) mb_prev = 0;
var mt_next = cssprop($set2.last().next(), "margin-top");
if (isNaN(mt_next)) mt_next = 0;
var mt_1 = cssprop($set1.first(), "margin-top");
var mb_1 = cssprop($set1.last(), "margin-bottom");
var mt_2 = cssprop($set2.first(), "margin-top");
var mb_2 = cssprop($set2.last(), "margin-bottom");
var h1 = $set1.last().offset().top + $set1.last().outerHeight() - $set1.first().offset().top;
var h2 = $set2.last().offset().top + $set2.last().outerHeight() - $set2.first().offset().top;
move1 = h2 + Math.max(mb_2, mt_1) + Math.max(mb_prev, mt_2) - Math.max(mb_prev, mt_1);
move2 = -h1 - Math.max(mb_1, mt_2) - Math.max(mb_prev, mt_1) + Math.max(mb_prev, mt_2);
move3 = move1 + $set1.first().offset().top + h1 - $set2.first().offset().top - h2 +
Math.max(mb_1,mt_next) - Math.max(mb_2,mt_next);
// let's move stuff
$set1.css('position', 'relative');
$set2.css('position', 'relative');
$set3.css('position', 'relative');
$set1.animate({'top': move1}, {duration: 1000});
$set3.animate({'top': move3}, {duration: 500});
$set2.animate({'top': move2}, {duration: 1000, complete: function() {
// rearrange the DOM and restore positioning when we're done moving
$set1.insertAfter($set2.last())
$set1.css({'position': 'static', 'top': 0});
$set2.css({'position': 'static', 'top': 0});
$set3.css({'position': 'static', 'top': 0});
}
});
}
or even better yet, use Quicksand
There's a jQuery plugin to do it now, I haven't tried it yet, but the demo seems to work nicely: http://biostall.com/swap-and-re-order-divs-smoothly-using-jquery-swapsie-plugin
See this fiddle: http://jsfiddle.net/maniator/26UNk/
$("#content ul").sortable({
opacity: 0.6,
cursor: 'move',
update: function() {
var order = $(this).sortable("serialize") + '&action=updateRecordsListings';
$.post("updateDB.php", order, function(theResponse) {
$("#response").html(theResponse);
});
}
});
That might help (it does have a dragging element to it)
精彩评论