トーストメッセージ
CoddyのHTMLジャーニー「JavaScriptの実践」セクションの一部。レッスン 8/27。
toast messageは、ユーザーにフィードバックを提供するために画面上に一時的に表示される小さな通知です。通常、数秒後に徐々に消えます。
基本的なHTML構造を作成します:
<div class="container">
<button id="showToast">Show Toast</button>
<div id="toast" class="hidden">This is a toast message!</div>
</div>トーストをスタイル設定するためにCSSを追加します。2つのクラスを使用します。.hiddenは非表示のままにするため、.showは表示するために使います。
.toast {
position: fixed;
bottom: 20px;
left: 50%;
background-color: #333;
color: white;
padding: 15px 25px;
}
.show {
opacity: 1;
}
.hidden {
display: none;
}次に、toast を表示および非表示にする JavaScript を追加します:
const showToastBtn = document.getElementById('showToast');
const toast = document.getElementById('toast');
showToastBtn.addEventListener('click', function() {
toast.classList.remove('hidden');
toast.classList.add('show');
setTimeout(function() {
toast.classList.remove('show');
toast.classList.add('hidden');
}, 3000);
});このコードは、button がクリックされると toast を表示し、3 seconds 後に自動的に非表示にします。
チャレンジ
簡単toast を見栄えよくし、表示・非表示の準備を整えることが目標です。
- ページのcenter at the bottomに toast message を配置するため、
position: fixedとbottomおよびleftを使用します。 - 読みやすくするため、background colorを設定し、text colorを変更します。
- メッセージが窮屈にならないように、paddingを追加します。
- 角を滑らかに見せます。
- デフォルトで非表示になるように(JavaScript が表示する前に)、opacity to 0に設定します。
自分で試してみよう
<!DOCTYPE html>
<html>
<head>
<title>Toast Notification Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>My Profile Settings</h1>
</header>
<main>
<p>Update your profile and save changes. A toast message will confirm your action.</p>
<button id="showToast">Save Changes</button>
</main>
<!-- トースト -->
<div id="toast" class="toast hidden">✅Your changes have been saved!</div>
<script src="script.js"></script>
</body>
</html>
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
JavaScriptの実践のすべてのレッスン
自分で練習してみよう: Webプレイグラウンド