初始隱藏 .box1,點擊 .box2 後,.box1 從 .box2 位置以動畫形式上升/移動到其原始預定位置。
.box1 的目標位置(top, left)。.box1 瞬移到 .box2 的位置並顯示。.animate() 過渡到目標位置。<style>
.box1, .box2 {
position: absolute;
width: 100px; height: 100px;
border: 1px solid #000;
}
.box1 {
display: none;
top: 100px; left: 100px; /* 目標位置 */
z-index: 100;
}
.box2 {
top: 200px; left: 200px; /* 觸發位置 */
}
</style>
<div class="box1">內容區域</div>
<div class="box2">點擊展開</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script>
$(function () {
var $box1 = $('.box1'),
$box2 = $('.box2'),
// 保存 box1 原始目標位置
targetPos = {
top: $box1.css('top'),
left: $box1.css('left')
};
// 將 box1 移至 box2 位置準備動畫
$box1.css({
top: $box2.css('top'),
left: $box2.css('left')
});
$box2.on('click', function () {
$box1.show().animate(targetPos, 1000); // 1秒動畫
});
});
</script>
| 步驟 | 代碼 | 說明 |
|---|---|---|
| 保存目標座標 | targetPos = {top: $box1.css('top'), ...} | 必須在修改 css 之前讀取 |
| 瞬移起始點 | $box1.css({top: $box2.css('top'), ...}) | 不觸發動畫,直接定位 |
| 顯示+動畫 | $box1.show().animate(targetPos, 1000) | 鏈式調用,先 show 再 animate |
easing: 'swing' 或 'linear' 控制緩動效果。.animate(targetPos, 1000, function(){ console.log('done'); })。box2 中心座標作為起始點。掌握「保存目標 → 瞬移起點 → show+animate」三步曲,輕鬆實現各類彈出層過渡動畫。