JQuery - 将 DOM 元素移动到新父元素的动画? [英] JQuery - animate moving DOM element to new parent?

查看:46
本文介绍了JQuery - 将 DOM 元素移动到新父元素的动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表格单元格内有一个图像标记,我想将其移动到另一个表格单元格,并为该移动设置动画.

I have an image tag inside of a table cell, that I'd love to move to another table cell, and have that movement animated.

代码看起来像这样...

The code looks something like this...

<td id="cell1"><img src="arrow.png" alt="Arrow"/></td>
<td id="cell2"></td>

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

I'd like to move "arrow.png" to "cell2", and have some kind of transition effect, preferably with JQuery.

有什么想法吗?

谢谢!

推荐答案

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

This is actually quite difficult because you have to remove and add it to the DOM but keep its position. I think you're looking for something like this. Basically we don't animate either the arrow in #cell1 or #cell2. We just create a new one in the body-tag and animate that. That way we don't have to worry about the table cell positions because we can position relative to the document.

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();
});

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

I think this should point you in the right direction.

这篇关于JQuery - 将 DOM 元素移动到新父元素的动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆