JQuery - 动画将DOM元素移动到新父元素?

31 javascript jquery animation dom jquery-ui

我在一个表格单元格中有一个图像标签,我很想移动到另一个表格单元格,并使该运动动画化.

代码看起来像这样......

<td id="cell1"><img src="arrow.png" alt="Arrow"/></td>
<td id="cell2"></td>
Run Code Online (Sandbox Code Playgroud)

我想将"arrow.png"移动到"cell2",并且具有某种过渡效果,最好是使用JQuery.

有任何想法吗?

谢谢!

Pim*_*ger 53

这实际上非常困难,因为您必须删除并将其添加到DOM但保持其位置.我想你正在寻找这样的东西.基本上我们没有动画箭头#cell1#cell2.我们只是在body-tag中创建一个新的,并为其设置动画.这样我们就不必担心表格单元格的位置,因为我们可以相对于文档进行定位.

var $old = $('#cell1 img');
//First we copy the arrow to the new table cell and get the offset to the document
var $new = $old.clone().appendTo('#cell2');
var newOffset = $new.offset();
//Get the old position relative to document
var oldOffset = $old.offset();
//we also clone old to the document for the animation
var $temp = $old.clone().appendTo('body');
//hide new and old and move $temp to position
//also big z-index, make sure to edit this to something that works with the page
$temp
  .css('position', 'absolute')
  .css('left', oldOffset.left)
  .css('top', oldOffset.top)
  .css('zIndex', 1000);
$new.hide();
$old.hide();
//animate the $temp to the position of the new img
$temp.animate( {'top': newOffset.top, 'left':newOffset.left}, 'slow', function(){
   //callback function, we remove $old and $temp and show $new
   $new.show();
   $old.remove();
   $temp.remove();
});
Run Code Online (Sandbox Code Playgroud)

我认为这应该指向正确的方向.


Dav*_*vy8 51

@Pim Jager的答案非常好,但是如果您对原始元素有对象引用,那么它们会因为原始元素被克隆替换而中断

我提出了我认为是一个稍微更清洁的解决方案,因为它只有一个克隆显示动画然后消失,将原始文件保留在新位置.

function moveAnimate(element, newParent){
    //Allow passing in either a jQuery object or selector
    element = $(element);
    newParent= $(newParent);

    var oldOffset = element.offset();
    element.appendTo(newParent);
    var newOffset = element.offset();

    var temp = element.clone().appendTo('body');
    temp.css({
        'position': 'absolute',
        'left': oldOffset.left,
        'top': oldOffset.top,
        'z-index': 1000
    });
    element.hide();
    temp.animate({'top': newOffset.top, 'left': newOffset.left}, 'slow', function(){
       element.show();
       temp.remove();
    });
}
Run Code Online (Sandbox Code Playgroud)

使用: moveAnimate('#ElementToMove', '#newContainer')

  • 我已经改进了你的代码片段,使它成为一个小的jQuery插件并清理一下:https://gist.github.com/MadLittleMods/7257ee631210215e368e (2认同)

Bal*_*an1 -3

JQuery http://docs.jquery.com/Downloading_jQuery
JQuery 效果http://docs.jquery.com/Effects/animate#paramsoptions


例子

 $("#go1").click(function(){
      $("#block1").animate( { width:"90%" }, { queue:false, duration:3000 } )
         .animate( { fontSize:"24px" }, 1500 )
         .animate( { borderRightWidth:"15px" }, 1500);
    });
Run Code Online (Sandbox Code Playgroud)