.moveToPointを設定した要素を表示後に少しだけ動かしたい場合のCSS例
css
@keyframes moveToPoint { from { transform: translate(0, 0); } to { /* 元の位置から「右に10px、上に20px」移動する場合 */ transform: translate(10px, 0px); } } /* 2. 基本スタイル */ .moveToPoint { position: relative; display: inline-block; /* 要素の種類によってはこれが必要 */ transform: translate(0, 0); /* 初期位置を確定させる */ } /* 3. クラスがついた時の処理 */ /* 詳細度を上げるため、クラスを繋げて記述します */ .moveToPoint.is-active { animation: moveToPoint 0.8s cubic-bezier(0.22, 1, 0.36, 1) forwards; animation-delay: 0.5s; will-change: transform; /* 滑らかにするための予約 */ }javascript
window.addEventListener('DOMContentLoaded', () => { // 1. 全ての .moveToPoint 要素を取得 const targets = document.querySelectorAll('.moveToPoint'); if (targets.length > 0) { const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { // 画面内に入った特定の要素だけにクラスを付与 entry.target.classList.add('is-active'); // その要素の監視を終了 observer.unobserve(entry.target); } }); }, { threshold: 0.2 }); // 全てのターゲットを監視対象に登録 targets.forEach(target => { observer.observe(target); }); } // 2. スクロール連動(パララックス)の処理 // こちらも複数ある場合は querySelectorAll で回すと確実です const movingImages = document.querySelectorAll('.moving-image'); if (movingImages.length > 0) { window.addEventListener('scroll', () => { let value = window.scrollY; movingImages.forEach(image => { image.style.top = value * 0.5 + 'px'; }); }); } });