[JS]アニメーション付きで要素の上下を入れ替える

JavaScript で要素の上下を入れ替えるには、before() や after() で DOM 上の順番を変えます。
ただしこれだけでは一瞬で入れ替わってしまうため、アニメーションを付けたい場合は「FLIP」と呼ばれる手法を使い、入れ替えた後の要素を元の位置から滑らかに移動させます。

DEMO

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>要素の入れ替えサンプル</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container py-3" id="card-list">
        <div class="card mb-3">
            <div class="card-header">
                <button type="button" class="btn btn-outline-secondary btn-sm" data-move="up" aria-label="上へ移動">▲</button>
                <button type="button" class="btn btn-outline-secondary btn-sm" data-move="down" aria-label="下へ移動">▼</button>
            </div>
            <div class="card-body">Card A</div>
        </div>

        <div class="card mb-3">
            <div class="card-header">
                <button type="button" class="btn btn-outline-secondary btn-sm" data-move="up" aria-label="上へ移動">▲</button>
                <button type="button" class="btn btn-outline-secondary btn-sm" data-move="down" aria-label="下へ移動">▼</button>
            </div>
            <div class="card-body">Card B<br>高さの違うカードでも<br>正しく入れ替わります</div>
        </div>

        <div class="card mb-3">
            <div class="card-header">
                <button type="button" class="btn btn-outline-secondary btn-sm" data-move="up" aria-label="上へ移動">▲</button>
                <button type="button" class="btn btn-outline-secondary btn-sm" data-move="down" aria-label="下へ移動">▼</button>
            </div>
            <div class="card-body">Card C</div>
        </div>
    </div>

    <script>
    const DURATION = 300;
    const list = document.getElementById('card-list');
    const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)');
    let animating = false;

    // ボタンごとではなく親要素でまとめてクリックを受け取る(イベント委譲)
    list.addEventListener('click', (event) => {
        const button = event.target.closest('[data-move]');
        if (!button || animating) return;

        const card = button.closest('.card');
        const isUp = button.dataset.move === 'up';
        const target = isUp ? card.previousElementSibling : card.nextElementSibling;
        if (!target) return;

        swap(card, target, isUp, button);
    });

    async function swap(card, target, isUp, button) {
        const cards = [card, target];

        // 1. 入れ替え前の位置を記録
        const before = cards.map((el) => el.getBoundingClientRect().top);

        // 2. DOM 上で先に入れ替える
        isUp ? target.before(card) : target.after(card);
        button.focus({ preventScroll: true }); // 移動で外れたフォーカスを戻す

        if (reduceMotion.matches) return;

        // 3. 元の位置から新しい位置へアニメーションさせる(FLIP)
        animating = true;
        const animations = cards.map((el, i) => {
            const dy = before[i] - el.getBoundingClientRect().top;
            return el.animate(
                [{ transform: `translateY(${dy}px)` }, { transform: 'none' }],
                { duration: DURATION, easing: 'ease-in-out' }
            );
        });

        await Promise.all(animations.map((a) => a.finished));
        animating = false;
    }
    </script>
</body>
</html>

仕組み

  1. First:入れ替える2つの要素の現在位置を getBoundingClientRect() で記録します。
  2. Last:before() / after() で、先に DOM 上の順番を入れ替えます。
  3. Invert:入れ替え後の位置と記録した位置の差を求め、translateY() でその分だけずらして、見かけ上は元の位置に戻します。
  4. Play:Web Animations API の animate() で、ずらした分を 0 に戻すアニメーションを再生します。

位置の差はブラウザに測らせるため、カードの高さや余白が違っても計算式を変える必要はありません。
また、アニメーション中の連打は無視し、OS の設定で「視差効果を減らす」(prefers-reduced-motion)が有効な場合はアニメーションせずに入れ替えます。




コメントを残す

メールアドレスが公開されることはありません。 ※ が付いている欄は必須項目です