Menu
CoddyTech

可关闭的横幅

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

可关闭横幅是一种通知栏或消息栏,会显示在页面顶部(或底部),用户可以将其关闭。这类横幅常用于显示重要信息,例如 Cookie 政策、公告或警告。它的关键特点是关闭(×)按钮,用户可以点击该按钮隐藏横幅,而无需刷新页面。

首先,我们来添加 HTML 结构:

<div class="banner" id="banner">
  <p>This is an important announcement!</p>
  <button id="closeBanner">X</button>
</div>

接下来,我们给横幅添加一些基本的 CSS 样式:

.banner {
  background-color: #1e90ff;
  color: white;
  padding: 15px 20px;
  text-align: center;
  position: relative;

}

.banner button {
  position: absolute;
  right: 10px;
  top: 10px;
  border: none;

  cursor: pointer;
}

最后,添加 JavaScript,让横幅可以关闭:

const banner = document.getElementById('banner');
const closeBtn = document.getElementById('closeBanner');

closeBtn.addEventListener('click', function() {
  banner.style.display = 'none';
});

点击关闭按钮后,横幅就会消失。

challenge icon

挑战

简单

我们希望用户点击关闭按钮时,横幅会消失。

  1. 添加一个事件监听器,让关闭按钮被点击时运行一个函数。
  2. 在这个函数中,将横幅元素的 display 属性设为 none,这样横幅就会隐藏。

亲手试试

<!DOCTYPE html>
<html>
<head>
  <title>Dismissible Banner Example</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>

  <!-- 横幅 -->
  <div class="banner" id="banner">
    <p>Big News! Our new course is live. Enroll today and get 30% off!</p>
    <button id="closeBanner">&times;</button>
  </div>

  <!-- 页面内容 -->
  <header class="hero">
    <h1>Welcome to CodeLearn</h1>
    <p>Practical lessons to sharpen your web development skills 🚀</p>
  </header>

  <main class="content">
    <section>
      <h2>Learn by Doing</h2>
      <p>Each lesson comes with tasks and challenges so you can practice immediately.</p>
    </section>

    <section>
      <h2>Topics We Cover</h2>
      <ul>
        <li>HTML & CSS basics</li>
        <li>JavaScript essentials</li>
        <li>Frontend projects</li>
        <li>Interactive UI components</li>
      </ul>
    </section>
  </main>

  <footer>
    <p>&copy; 2025 CodeLearn. All rights reserved.</p>
  </footer>

  <script src="script.js"></script>
</body>
</html>
quiz icon自我测试

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

JavaScript 实战中的所有课

自己练习: Web 在线编辑器