土曜日, 2月 15, 2025

Let's start JavaScript 56 
HTML上で入力した文字を1文字ずつ点滅

HTML上で入力した文字を1文字ずつ点滅させてみました。

<!-- index.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>文字の点滅アニメーション</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 20px;
background-color: whitesmoke;
}
#output {
font-size: 24px;
margin-top: 20px;
white-space: pre-wrap;
display: flex;
justify-content: center;
gap: 5px;
}
.letter {
opacity: 1;
animation: blink 1s infinite;
}
@keyframes blink {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0;
}
}
</style>
</head>
<body>
<h2>入力した文字を1文字ずつ点滅</h2>
<p>文字列を入力してください:</p>
<input type="text" id="inputText"
placeholder="ここに文字を入力">
<button onclick="startAnimation()">
アニメーション開始</button>

<div id="output"></div>

<script>
function startAnimation() {
const inputText =
document.getElementById("inputText").value;
const output = document.getElementById("output");
output.innerHTML = ""; // 初期化

// 文字列を1文字ずつ分割してアニメーションを適用
inputText.split("").forEach((char, index) => {
const span = document.createElement("span");
span.textContent = char;
span.classList.add("letter");

// アニメーションの遅延を設定
span.style.animationDelay = `${index * 0.3}s`;
output.appendChild(span);
});
}
</script>
</body>
</html>
<!-- index.html -->
 
実行したら点滅させたい文字を入力し[アニメーション開始]をクリックするだけです。


こんな感じです。