我有一些元素,当我单击它们时,我想移动到其他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。
答案 0 :(得分:6)
position:fixed
的形式创建元素的“飞行克隆”。visibility:hidden
或opacity:0
/**
* 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>
答案 1 :(得分:-1)
我删除了Roko的答案,看看哪种方法可以做什么。
function flyMeTo( orig, destination ) {
var $copy = $(orig).clone().insertAfter($(orig)); // duplicate the original button element
$copy.css({position:"fixed"}); // dunno what this is for
$(orig).css({opacity:0}).appendTo(destination); // make the orig invisible then append it to the other div still invisible
var end = orig.getBoundingClientRect(); // now that the orig is at the new location, get its position
$copy.animate({left:end.left, top:end.top}); // animate the duplicate to make it go to that position
}