前言
在表单校验、接口请求反馈场景,我们经常需要轻量的顶部 toast 气泡提示:操作成功展示绿色提示,失败展示红色警告,2 秒之后自动消失。很多同学第一反应引入 Element UI、Layer 等第三方弹窗组件。但小型项目不想引入额外库,我们完全可以原生 HTML+CSS+jQuery 手写一套轻量消息气泡。
本文就基于手写的成功 / 错误顶部提示框完整代码,讲解实现思路、样式细节、业务坑点、优化方案。
技术栈:HTML + CSS + jQuery 效果:页面顶部悬浮提示,成功绿色,错误红色,2 秒自动关闭。
完整原始代码
HTML 结构
<!-- 成功提示框 修改图片路径 -->
<div id="success">
<div class="successCenter">
<img id="successImg" src="./yes.png" alt="" />
<span class="successText"></span>
</div>
</div>
<!-- 错误提示框 -->
<div id="error">
<div class="errorCenter">
<img id="errorImg" src="./error.png" alt="" />
<span class="errorText"></span>
</div>
</div>
结构说明:
- 外层
#success/#error:fixed 定位,控制整体显示隐藏; - 内部
successCenter/errorCenter:flex 容器,放图标 + 文字; - img 为状态图标,span 用来动态填充提示文本。
CSS 样式
/*成功弹窗*/
.successText {
color: #28C445;
font-family: YouYuan;
}
/* 错误弹窗 */
#error {
z-index: 51;
width: 100%;
height: 35px;
display: flex;
top: 10vh;
position: fixed;
justify-content: center;
align-items: center;
display: none;
}
#errorImg {
margin-right: 5px;
width: 15px;
height: 15px;
}
.errorCenter {
padding: 0 10px;
display: flex;
align-items: center;
border-radius: 6px;
justify-content: center;
height: 35px;
background-color: rgb(254, 238, 238);
}
.errorText {
color: #e70a0a;
font-family: YouYuan;
}
注意:代码中
#error写了两次 display 属性,后面display:none会覆盖前面display:flex;页面初始化默认隐藏弹窗。success 弹窗 CSS 和 error 结构保持一致,修改颜色背景即可。
JavaScript 业务函数
// 弹窗显示函数
/**
* 成功 失败弹窗函数
* 直接调用函数名 然后传入要显示的文字
* @param {string} message - 弹窗显示的文字
*/
// 成功弹窗
function showSuccess(message) {
$(".successText").html(message);
$("#success").css('display', 'flex');
setTimeout(function () {
$("#success").css('display', 'none');
}, 2000);
}
// 失败弹窗
function showError(message) {
$(".errorText").html(message);
$("#error").css('display', 'flex');
setTimeout(function () {
$("#error").css('display', 'none');
}, 2000);
}
使用方式
//业务中直接调用
showSuccess("提交成功!");
showError("请上传图片");
实现思路拆解
- 定位方案 :
position:fixed; top:10vh; width:100%,固定在视口顶部,不受页面滚动影响;外层 100% 宽度,内部容器 flex 水平居中。 - 显示隐藏 :通过
display:none / flex切换;display:flex 保证内部图标文字 flex 布局。 - 动态文本 :jQuery
.html()把传入消息填充到 span 标签。 - 自动关闭 :
setTimeout定时器 2000 毫秒后把 display 设置为 none,实现自动消失。 - 视觉区分:成功绿色文字 + 浅绿背景,错误红色文字 + 浅红背景,搭配图标,用户一眼区分状态。
总结
- 简单消息气泡弹窗核心技术点:
position:fixed悬浮定位 + display 控制显隐 + setTimeout 自动关闭; - 多次调用弹窗,一定要清除旧定时器,否则会出现弹窗消失时机错乱 bug;
- 不要写两套几乎一样 HTML/CSS,用 class 做类型区分,降低维护成本;
- z-index 设置足够大,防止弹窗被页面其他元素遮挡;
- 追求更好体验,可以使用 opacity+transition 实现淡入动画,摒弃粗暴 display 切换。