2013-07-10 168 views
1

基本上我有两个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$targetli不同ul

div.row > div.col > ul > li 
      div.col > ul > li 

(每个相邻的相关列表位于它自己的div.col中;位置被继承为静态)

我希望能够做到: $source.animateTo($target)

+0

这实际上依赖于HTML/CSS标记,因为位置属性与此问题极其相关。虽然我认为这种方法存在一些奇怪的方法,但是他们需要很多难看的DOM操作。 – Ennui

+0

@Ennui编辑问题以包含我的标记结构/约束。 –

回答

1

使用jQuery的$ .offset功能 http://api.jquery.com/offset/

var offset = $('#containerToMoveTo').offset(); 

$('#elementToAnimate').animate({ 
    top: offset.top, 
    left: offset.left 
}); 

应该这样做,如果没有,请尝试给#elementToAnimate位置绝对正确的动画之前。

$('#elementToAnimate').css('position', 'absolute');