通知横幅是网页中常见的交互组件,主要用于展示临时提示、活动公告、系统通知等内容,通常固定在页面顶部或底部,用户可以通过关闭按钮隐藏横幅。下面我们一步步实现这个组件。

基础HTML结构搭建
首先我们需要搭建横幅的基础HTML结构,包含横幅容器、内容区域和关闭按钮三个核心部分。结构要语义化,方便后续样式和交互开发。
<div class="alert-banner">
<div class="banner-content">
<span class="banner-text">系统维护通知:本周六凌晨2点到4点将进行系统升级,期间部分功能暂时不可用</span>
</div>
<button class="banner-close">×</button>
</div>这里使用div作为横幅容器,内部用span存放通知文本,button作为关闭按钮,结构简洁清晰,没有多余的嵌套。
CSS样式美化
基础结构搭建完成后,我们需要通过CSS让横幅显示在正确位置,并且样式美观。这里将横幅固定在页面顶部,添加背景色和文字样式。
.alert-banner {
position: fixed;
top: 0;
left: 0;
width: 100%;
background-color: #fff3cd;
color: #856404;
padding: 12px 20px;
display: flex;
justify-content: space-between;
align-items: center;
box-sizing: border-box;
z-index: 9999;
border-bottom: 1px solid #ffeaa7;
}
.banner-content {
flex: 1;
margin-right: 20px;
}
.banner-text {
font-size: 14px;
line-height: 1.5;
}
.banner-close {
background: none;
border: none;
font-size: 20px;
color: #856404;
cursor: pointer;
padding: 0 5px;
line-height: 1;
}
.banner-close:hover {
color: #664d03;
}样式中设置了position: fixed让横幅固定在顶部,z-index保证横幅显示在其他内容上方,flex布局让内容和关闭按钮对齐,整体样式简洁醒目。
JavaScript添加交互功能
横幅需要支持关闭功能,点击关闭按钮后横幅消失,这部分逻辑通过JavaScript实现。
// 获取横幅和关闭按钮元素
const alertBanner = document.querySelector('.alert-banner');
const closeBtn = document.querySelector('.banner-close');
// 给关闭按钮添加点击事件
closeBtn.addEventListener('click', function() {
// 隐藏横幅
alertBanner.style.display = 'none';
});代码先获取对应的DOM元素,然后给关闭按钮绑定点击事件,点击时修改横幅的display属性为none,实现隐藏效果。
完整示例整合
将前面的HTML、CSS、JavaScript代码整合到一起,就是一个完整的可运行的通知横幅组件。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>通知横幅示例</title>
<style>
.alert-banner {
position: fixed;
top: 0;
left: 0;
width: 100%;
background-color: #fff3cd;
color: #856404;
padding: 12px 20px;
display: flex;
justify-content: space-between;
align-items: center;
box-sizing: border-box;
z-index: 9999;
border-bottom: 1px solid #ffeaa7;
}
.banner-content {
flex: 1;
margin-right: 20px;
}
.banner-text {
font-size: 14px;
line-height: 1.5;
}
.banner-close {
background: none;
border: none;
font-size: 20px;
color: #856404;
cursor: pointer;
padding: 0 5px;
line-height: 1;
}
.banner-close:hover {
color: #664d03;
}
.main-content {
margin-top: 60px;
padding: 20px;
}
</style>
</head>
<body>
<div class="alert-banner">
<div class="banner-content">
<span class="banner-text">系统维护通知:本周六凌晨2点到4点将进行系统升级,期间部分功能暂时不可用</span>
</div>
<button class="banner-close">×</button>
</div>
<div class="main-content">
<h1>页面主体内容</h1>
<p>这里是页面的其他内容,通知横幅会固定在顶部,不会遮挡主体内容。</p>
</div>
<script>
const alertBanner = document.querySelector('.alert-banner');
const closeBtn = document.querySelector('.banner-close');
closeBtn.addEventListener('click', function() {
alertBanner.style.display = 'none';
});
</script>
</body>
</html>这个完整示例可以直接复制到HTML文件中运行,横幅会固定在页面顶部,点击关闭按钮即可隐藏,满足基础的通知横幅使用需求。
HTMLalert_bannerCSSJavaScript修改时间:2026-06-10 05:21:24