需求
最近使用bootstrap时,需要一个弹窗提示用户登录失败。bootstrap提供了alert组件来满足弹窗提示的功能,但是没有自动关闭功能,只提供了一个可以通过点击’ x '号关闭的弹窗。详情:bootstrap警告框。
这样对用户并不太友好,例如elementui中的弹框,显示一段时间后自动消失。起到了提示作用即可。
实现
利用window.setTimeout
延时一定时间后,再关闭弹框。
为弹框添加’ hide ‘类,即默认隐藏。当需要显示时,再添加’ show ‘类,显示弹框。延时一段时间后,去除’ show '类,达到再次隐藏的目的。(这里使用jquery实现)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 引入最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<style>
.alert{
position: fixed;
width: 50%;
margin-left: 20%;
z-index: 2000;
}
</style>
</head>
<body>
<div class="alert alert-danger hide">这是一个失败提示!</div>
<div class="alert alert-success hide">这是一个成功提示!</div>
<div class="btn">
<button class="btn btn-info" id="btn1">失败提示</button><br><br>
<button class="btn btn-info" id="btn2">成功提示</button>
</div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script>
$("#btn1").click(function(){
$(".alert-danger").addClass("show");
window.setTimeout(function(){
$(".alert-danger").removeClass("show");
},1000);//显示的时间
})
$("#btn2").click(function(){
$(".alert-success").addClass("show");
window.setTimeout(function(){
$(".alert-success").removeClass("show");
},1000);//显示的时间
})
</script>
</html>
这里我测试使用鼠标点击事件实现弹框提示,可以根据需求自己更改。例如接收后端传来的参数来显示成功还是失败弹框。
效果
失败提示
成功提示