基本上,我有两个jQuery包装的元素$source
和$target
,其中$source
是填充程序/占位符。
我想将$source
设置为$target
的位置。动画之后,我正在执行$target.replaceWith($source);
无论$source
和$target
在DOM中的什么位置,我都必须能够做到这一点。是否有jQuery插件/简便的方法来完成此操作?
至于我要解决的问题,我有两个列表,并且试图将一个列表中的最后一项动画化为另一个列表的开头。
这是我的目的:
var moveItem = function ($sourceItem, $targetItem, callback, before) {
var targetCord = $targetItem.css('position', 'absolute').offset();
$targetItem.css('position', 'static');
var sourceCord = $sourceItem.position();
$targetItem[before? 'before': 'after']('<li class="shim"></li>');
//diag('Shim Created.');
var $newlyAddedShim = $targetItem[before ? 'prev' : 'next']();
$sourceItem.css('position', 'absolute')
.css({ left: sourceCord.left, top: sourceCord.top })
.animate({ left: targetCord.left, top: targetCord.top }, 'slow', function () {
$newlyAddedShim.replaceWith($sourceItem.css('position', 'static'));
callback();
});
};
如果不可能有通用的解决方案,则这是我必须限制的标记结构,其中
$source
和$target
在不同的li
中是ul
:div.row > div.col > ul > li
div.col > ul > li
(每个相邻的相关列表都在其自己的div.col中;位置继承为静态)
我希望能够做到:
$source.animateTo($target)
最佳答案
使用jQuery的$ .offset函数
http://api.jquery.com/offset/
var offset = $('#containerToMoveTo').offset();
$('#elementToAnimate').animate({
top: offset.top,
left: offset.left
});
应该这样做,否则请尝试在动画之前绝对赋予#elementToAnimate位置。
$('#elementToAnimate').css('position', 'absolute');