一文字ずつふわっとランダムに浮かび上がる見出しのアニメーションを実装してみたのでメモ。
サンプル
ふわっと浮かび上がる見出し
HTML
<h3 class="midashi-03 fade-title">ふわっと浮かび上がる見出し</h3>CSS
.fade-title span {
visibility: hidden;
opacity: 0;
display: inline-block;
transform: translateY(6px);
}
.fade-title.is-active span {
visibility: visible;
animation: fadeUp 1.2s forwards;
}
@keyframes fadeUp {
to {
opacity: 1;
transform: translateY(0);
}
}ふわっとのスピードを変えたい場合は、以下の数字を調整します。
.fade-title.is-active span {
animation: fadeUp 1s forwards; /* ここを微調整0.8s~1.4s */
}JS
.fade-title要素が画面に入ったら.is-activeを付与。
.fade-title内の文字を一文字ずつ<span>で囲い、ランダムなanimationDelayを付与。
document.addEventListener('DOMContentLoaded', () => {
const titles = document.querySelectorAll('.fade-title');
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('is-active');
observer.unobserve(entry.target);
}
});
}, {
threshold: 0,
rootMargin: '0px 0px -10% 0px'
});
titles.forEach(title => {
const text = title.textContent;
title.textContent = '';
text.split('').forEach(char => {
const span = document.createElement('span');
span.textContent = char;
const delay = Math.random() * 0.8;
span.style.animationDelay = delay + 's';
title.appendChild(span);
});
observer.observe(title);
});
});お試しあれ!