初心者でも少しリッチなフェードインアニメーションが簡単に実装できるコード。
スクロールに連動して、スルッとフェードインしてくるclip-pathを使ったアニメーション。
軽量+分かりやすいコードで、クラスを変えるだけで色々な方向からフェードインできる仕様。
HTML
<div class="ugkClip">
<div class="clipAnime leftTop">
<p>左上からイン</p>
</div>
<div class="clipAnime rightTop">
<p>右上からイン</p>
</div>
<div class="clipAnime left">
<p>左からイン</p>
</div>
<div class="clipAnime right">
<p>右からイン</p>
</div>
<div class="clipAnime top">
<p>上からイン</p>
</div>
<div class="clipAnime bottom">
<p>下からイン</p>
</div>
</div>
CSS
.clipAnime {
/*ここで全体のアニメーション秒数を設定*/
transition: all ease 1.5s;
}
/*classに応じて出現前の位置設定*/
.leftTop {
clip-path: polygon(0 0, 0 0, 0 0);
}
.rightTop {
clip-path: polygon(100% 0, 100% 0, 100% 0);
}
.left {
clip-path: polygon(0 0, 0 0, 0 100%, 0 100%);
}
.right {
clip-path: polygon(100% 0, 100% 0, 100% 100%, 100% 100%);
}
.top {
clip-path: polygon(0 0, 100% 0, 100% 0, 0 0);
}
.bottom {
clip-path: polygon(0 100%, 100% 100%, 100% 100%, 0 100%);
}
/*画面に入った後は元の位置や大きさに戻る*/
.fadeIn.leftTop {
clip-path: polygon(0 0, 200% 0, 0 200%);
}
.fadeIn.rightTop {
clip-path: polygon(100% 0, -200% 0, 100% 200%);
}
.fadeIn.left {
clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%);
}
.fadeIn.right {
clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%);
}
.fadeIn.top {
clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%);
}
.fadeIn.bottom {
clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%);
}
/*ボックスレイアウト用*/
.ugkClip div {
width: 400px;
max-width: 100%;
margin: 0 auto 80px;
background-color: #838383;
padding: 50px 0;
text-align: center;
color: #fff;
}
JS
(() => {
const run = () => {
const els = document.querySelectorAll('.clipAnime');
if (!els.length) return;
const update = () => {
const y = window.pageYOffset || document.documentElement.scrollTop;
const vh = window.innerHeight || document.documentElement.clientHeight;
els.forEach((el) => {
//↓要素の80px下が起点(出すタイミングによって数値を変更)
const top = el.getBoundingClientRect().top + y + 80;
//↓画面内に入った時アニメーションを毎回発生させる場合↓
el.classList.toggle('fadeIn', y >= top - vh);
//↓アニメーションを初回のみにしたい場合↓
//if (y >= top - vh) el.classList.add('fadeIn');
});
};
const onChange = () => requestAnimationFrame(update);
window.addEventListener('scroll', onChange, { passive: true });
update();
};
document.readyState === 'loading'
? document.addEventListener('DOMContentLoaded', run)
: run();
})();
フェードイン実装方法
実際に使用するときはcssとjsをサイトにコピペし、フェードインさせたい要素全てにclipAnimeクラスを付けます。
それぞれの動きに合わせて以下のクラスを追加してください。
- 左上からイン:leftTop
- 右上からイン:rightTop
- 左からイン:left
- 右からイン:right
- 上からイン:top
- 下からイン:bottom
実際の動き
左上からイン
右上からイン
左からイン
右からイン
上からイン
下からイン

コメント