遮罩层
- 原理:利用绝对定位和z-index,在所有组件上层添加一个窗口大小的div,利用js控制现实或隐藏
- 实现:
// html
<div id="mask" class="hidden"></div>
// css
#mask {
width: 100vw;
height: 100vh;
position: absolute;
/* 给遮罩层绝对定位 */
z-index: 10;
/* 设置z-index值 */
background-color: rgba(0, 0, 0, 0.4);
}
.hidden {
display: none;
}
// js
let mask = document.getElementById("mask");
mask.setAttribute("class", ""); //显示遮罩层
mask.setAttribute("class", "hidden"); //隐藏遮罩层
消息框
- 原理:利用绝对定位和z-index,在遮罩层上层添加一个div,利用js控制现实或隐藏、click事件以及文本内容
- 实现:
// html
<div id="msg-box" class="hidden">
<p id="msg"></p>
<button id="msg-box-btn" onclick="hideMsg()">知道了</button>
</div>
// css
#msg-box {
width: 70vw;
background-color: black;
z-index: 11;
position: absolute;
margin-top: 38vh;
margin-left: 15vw;
border-radius: 8px;
color: white;
text-align: center;
font-size: 26px;
}
#msg-box p {
margin-top: 5.5vh;
margin-bottom: 4.5vh;
}
#msg-box button {
font-size: 18px;
width: 50vw;
height: 5.5vh;
margin-bottom: 4.5vh;
background-color: #e62528;
color: white;
outline: none;
border: 0px;
text-align: center;
border-radius: 6px;
}
// js
let msgBox = document.getElementById("msg-box");
msgBox.setAttribute("class", ""); // 显示消息框
document.getElementById("msg").innerText = "msg"; // 设置文本内容
整体实现(可直接使用)
// html
<!-- 遮罩层 -->
<div id="mask" class="hidden"></div>
<div id="msg-box" class="hidden">
<p id="msg"></p>
<button id="msg-box-btn" onclick="hideMsg()">知道了</button>
</div>
// css
/* 遮罩层样式设置 */
#mask {
width: 100vw;
height: 100vh;
position: absolute;
/* 给遮罩层绝对定位 */
z-index: 10;
/* 设置z-index值(要小于弹出框) */
background-color: rgba(0, 0, 0, 0.4);
}
#msg-box {
width: 70vw;
background-color: black;
z-index: 11;
position: absolute;
margin-top: 38vh;
margin-left: 15vw;
border-radius: 8px;
color: white;
text-align: center;
font-size: 26px;
}
#msg-box p {
margin-top: 5.5vh;
margin-bottom: 4.5vh;
}
#msg-box button {
font-size: 18px;
width: 50vw;
height: 5.5vh;
margin-bottom: 4.5vh;
background-color: #e62528;
color: white;
outline: none;
border: 0px;
text-align: center;
border-radius: 6px;
}
// js
/*
* 弹出提示框
* msg: 消息文本
* btnVisiable: 是否显示按钮
* maskCloseable: 是否可以点击遮罩层关闭消息框
*/
function msg(msg, btnVisiable = true, maskCloseable = true) {
let mask = document.getElementById("mask");
let msgBox = document.getElementById("msg-box");
let msgBoxBtn = document.getElementById("msg-box-btn");
mask.setAttribute("class", "");
if(maskCloseable) {
mask.setAttribute("onclick", "hideMsg()");
}
else {
mask.setAttribute("onclick", "");
}
msgBox.setAttribute("class", "");
if(btnVisiable) {
msgBoxBtn.setAttribute("class", "");
}
else {
msgBoxBtn.setAttribute("class", "hidden");
}
document.getElementById("msg").innerText = msg;
}
/*
* 隐藏提示框
*/
function hideMsg() {
document.getElementById("mask").setAttribute("class", "hidden");
document.getElementById("msg-box").setAttribute("class", "hidden");
document.getElementById("msg").innerText = "";
}
# 前端