首页 > 解决方案 > appendTo后如何让一个div飞到另一个div

问题描述

我有一些元素,我想在单击它们时将它们移动到其他 div。我找到了appendTo,但我不知道如何让元素在过渡中飞到另一个 div。

<div id="top">
  <button id="b1">B1</button>
</div>
<br>
<br>
<br>
<br>
<div id="bottom">
  <button id="b2">B2</button>
</div>

<script>
$('#b1').click(function() {
  $('#b1').appendTo($('#bottom'));
})

$('#b2').click(function() {
  $('#b2').appendTo($('#top'));
})
</script>

有没有一种简单的方法可以让按钮在被点击后“飞起来”?现在,我只是让它们淡出并进入新的 div。

标签: javascriptjquery

解决方案


  1. 在当前坐标处创建元素的“飞行克隆” 。position:fixed
  2. 将元素附加到目标
  3. 使用或隐藏元素visibility:hiddenopacity:0
  4. 将克隆从起始坐标动画到元素的新坐标
  5. 摧毁克隆
  6. 使元素可见
  7. 如果元素已经在目的地,则防止飞行(即:在后续调用中)

/** 
 * Fly element to destination parent
 * Use like: flyMeTo("#bird", "#destinationParent")
 * @param el {String} Selector (or `this`) of the flying element
 * @param destination {String} Destination parent selector
 * @param prepend {Boolean} Optional. Set to true to use prepend (instead of append)
 */
function flyMeTo(elem, destination, prepend) {

  var $elem = $(elem);
  var $dest = $(destination);
  
  // Early exit - if already in destination
  if($elem.parent().is(destination)) return;
  
  var $klon = $elem.clone().insertAfter($elem);
  var start = elem.getBoundingClientRect();

  $klon.css({position:"fixed", zIndex:9999, left:start.left, top:start.top, pointerEvents:'none'});
  $elem.css({opacity:0})[prepend?'prependTo':'appendTo']( $dest );

  var end = elem.getBoundingClientRect(); // Get new coordinates after append/prepend
  $klon.animate({left:end.left, top:end.top}, 600, function() {
    $klon.remove();         // Remove flying clone once it reaches destination
    $elem.css({opacity:1}); // Show original Element
  });
}


// DEMO:
$('#b1').click(function() {
  flyMeTo( this, '#bottom', true ); // By passing `true` it will prepend!
});
$('#b2').click(function() {
  flyMeTo( this, '#top' );
});
body {
  height: 200vh;
}
<br>
<br>
<br>
<div id="top">
  <button id="b1">B1</button>
</div>
<br>
<br>
<br>
<br>
<div id="bottom">
  <button id="b2">B2</button>
</div>

<script src="//code.jquery.com/jquery-3.1.0.js"></script>


推荐阅读