appendTo()动画

尝试使用jQuery或jQuery-UI将元素从一个元素附加到另一个元素时实现任何移动效果。

$('#i-am-moving-slow').appendTo('#div2');

请帮忙。 谢谢。

编辑: http : //jsfiddle.net/5936t/

您可以将元素的克隆附加到新点,但保持隐藏。 将原始元素设置为新点,然后删除旧元素,并显示新元素。

我做了一个插件来做到这一点。 试试这个:

 $.fn.animateAppendTo = function(sel, speed) { var $this = this, newEle = $this.clone(true).appendTo(sel), newPos = newEle.position(); newEle.hide(); $this.css('position', 'absolute').animate(newPos, speed, function() { newEle.show(); $this.remove(); }); return newEle; }; $('#i-am-moving-slow').click(function() { $(this).animateAppendTo('#div2', 1000); });​ 

演示: http : //jsfiddle.net/5936t/36/

我知道这个问题已经解决了,但我决定改进Rocket的答案。 我需要为appendTo,prependTo,insertBefore和insertAfter的行为设置动画,我还希望能够自定义缓动并提供回调,就像使用$.fn.animate()

此外,我的函数留下了原始元素而不是它的克隆,其行为与appendTo完全相同。 因此,如果您对脚本变量中存在的元素有任何现有引用,它们就不会中断。

我也使用position:relative而不是position:absolute来做动画,所以如果元素的宽度是其容器的100%,它将不会跳出并在动画期间占据窗口的100%。 但是,在动画结束时,无论新容器的宽度是多少,它都会跳到100%。

这是我的解决方案:

 $.fn.animateTo = function(appendTo, destination, duration, easing, complete) { if(appendTo !== 'appendTo' && appendTo !== 'prependTo' && appendTo !== 'insertBefore' && appendTo !== 'insertAfter') return this; var target = this.clone(true).css('visibility','hidden')[appendTo](destination); this.css({ 'position' : 'relative', 'top' : '0px', 'left' : '0px' }).animate({ 'top' : (target.offset().top - this.offset().top)+'px', 'left' : (target.offset().left - this.offset().left)+'px' }, duration, easing, function() { target.replaceWith($(this)); $(this).css({ 'position' : 'static', 'top' : '', 'left' : '' }); if($.isFunction(complete)) complete.call(this); }); } 

用法:

 // basic usage $("#i-am-moving-slow").animateTo('appendTo', '#div2'); // advanced usage $("#i-am-moving-slow").animateTo('insertAfter', '#some-other-div', 'linear', function() { console.log("animation completed on ", this); }); 

durationeasing将被委托给animate调用,所以如果你把它们留出来,它们将作为undefined传入,jQuery将使用默认值。 在元素替换发生在动画complete时调用complete ,并将其设置为等待动画元素,就像$.fn.animate()的回调一样。

可能这就是你想要的

HTML

 
i-am-moving-slow
div2

JS

 $('#div2') .append($('#i-am-moving-slow') .css({'margin-left':-$(this).width()+'px'}) .delay(500) .animate({'margin-left':'0px'}, 'slow'));​ 

这是一个例子 。

如果你想附加一个副本,那么你应该克隆它, 这是使用克隆的另一个例子 。