Menu
CoddyTech

Toast 消息

本课属于 Coddy HTML 学习旅程的“JavaScript 实战”单元。第 8 课,共 27 课。

toast 消息是一种简短显示在屏幕上的小通知,用来向用户提供反馈。它通常会在几秒后淡出。

创建一个基本的 HTML 结构:

<div class="container">
    <button id="showToast">Show Toast</button>
    <div id="toast" class="hidden">This is a toast message!</div>
</div>

添加一些 CSS 来设置提示框的样式。我们使用两个类:.hidden 用来让它保持隐藏,.show 用来让它显示出来。

.toast {
    position: fixed;
    bottom: 20px;
    left: 50%;
    background-color: #333;
    color: white;
    padding: 15px 25px;
}
.show {
    opacity: 1;
}
.hidden {
    display: none;
}

现在添加 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);
});

点击按钮时,这段代码会显示提示消息,并在 3 秒后自动将其隐藏。

challenge icon

挑战

简单

你的目标是让 toast 看起来美观,并做好显示和隐藏的准备。

  1. 使用 position: fixed、bottom 和 left,将 toast 消息放在页面底部中央。
  2. 设置背景颜色并更改文字颜色,让内容清晰易读。
  3. 添加一些内边距,避免消息显得拥挤。
  4. 让边角看起来圆润一些。
  5. 将 opacity 设为 0,这样默认情况下消息会隐藏(在 JavaScript 显示它之前)。

亲手试试

<!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>
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

JavaScript 实战中的所有课

自己练习: Web 在线编辑器