文字を1文字ずつアニメーションさせるためのjavascript css HTML

html

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Animation Sample</title>
	<link rel="stylesheet" href="style.css">
</head>
<body>
	<p class="sample">サンプル</p>
	<script src="script.js"></script>
</body>
</html>

css

.sample {
	position: relative;
	font-size: 30px;
}

.sample span {
	display: inline-block;
	position: absolute;
	animation: move 1s forwards;
}

@keyframes move {
	from {
		opacity: 0;
		transform: translateY(-50px);
	}
	to {
		opacity: 1;
		transform: translateY(0px);
	}
}

js

const sample = document.querySelector('.sample');
const text = sample.textContent;
const length = text.length;
sample.textContent = '';

for (let i = 0; i < length; i++) {
	const char = text.charAt(i);
	const span = document.createElement('span');
	span.textContent = char;
	span.style.animationDelay = i * 100 + 'ms';
	sample.appendChild(span);
}

ここでは、HTMLファイルでCSSファイルとJavaScriptファイルをそれぞれ読み込んでいます。CSSファイルでは、.sampleクラスとその中のspan要素にスタイルを適用しています。JavaScriptファイルでは、テキストを一文字ずつspan要素に包んで、それぞれにアニメーションの遅延時間を設定しています。

この記事が気に入ったらサポートをしてみませんか?