利用ES6中的类制作一个简单Loading遮罩层
这是一个使用ES6的类,制作的一个简单的Loading遮罩层,可以展示Loading动画,或显示指定的文本,还可以设置遮罩层多少毫秒以后关闭,或者手动关闭遮罩层。
代码如下:
class Info{
// 构造函数
constructor(settings){
this.configure = settings;
this.rootNode = null;
this.init();
}
// 初始化函数
init(){
let body = document.querySelector("body");
body.insertAdjacentHTML("beforeend", "<div id='mask'></div>");
this.rootNode = document.getElementById("mask");
}
// 判断是否有定时器
show(){
if(this.configure.time){
this.maskShow();
let that = this;
setTimeout(function(){
that.disappear();
}, that.configure.time);
}else{
this.maskShow();
}
}
// 调用maskShow()函数显示遮罩层
maskShow(){
this.rootNode.classList.add("mask");
this.rootNode.style.display = "flex";
// 判断显示Loading动画还是显示指定的文本
if(this.configure.isLoading){
this.rootNode.insertAdjacentHTML("beforeend", "<div id='mask-animation'></div>");
let maksAnimation = document.getElementById("mask-animation");
maksAnimation.insertAdjacentHTML("beforeend", `
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
`);
}else{
// this.rootNode.style.background = "none";
this.rootNode.insertAdjacentHTML("beforeend", "<p id='mask-info'>"+ this.configure.text +"</p>");
}
}
// 调用disappear()函数隐藏遮罩层
disappear(){
this.rootNode.style.display = "none";
this.rootNode.classList.remove("mask");
}
}
.mask{
width: 100%;
height: 100vh;
position: absolute;
top: 0;
left: 0;
z-index: 99999999;
background-color: rgba(255, 255, 255, 0.9);
display: flex;
justify-content: center;
align-items: center;
}
#mask-info{
width: 400px;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
background-color: #fab1a0;
color: white;
border-radius: 5px;
font-size: 1.5rem;
user-select: none;
position: absolute;
transform: translateY(-80vh);
animation: down 1s ease 0s 1 forwards;
}
#mask-animation{
width: 12rem;
height: 12rem;
display: flex;
justify-content: center;
align-items: center;
}
span{
display: block;
width: 15px;
height: 60px;
background-color: #1abc9c;
margin: 0 5px;
}
span:nth-child(1){
animation: up2 0.8s linear infinite alternate-reverse;
}
span:nth-child(2){
animation: up 0.8s linear infinite alternate-reverse;
animation-delay: 0.3s;
}
span:nth-child(3){
animation: up 0.8s linear infinite alternate-reverse;
animation-delay: 0.4s;
}
span:nth-child(4){
animation: up 0.8s linear infinite alternate-reverse;
animation-delay: 0.3s;
}
span:nth-child(5){
animation: up2 0.8s linear infinite alternate-reverse;
}
@keyframes up{
0%{
height: 30px;
}
100%{
height: 120px;
}
}
@keyframes up2{
0%{
height: 30px;
}
100%{
height: 60px;
}
}
@keyframes down{
to{
transform: translateY(0);
}
}
在HTML中调用:
// 必须先引用上面的JS和CSS
<link rel="stylesheet" href="./mask.css">
<script src="./mask.js"></script>
<script>
const info = new Info({
isLoading: true, // 是否要显示动画
// 为true时显示动画,为false时,显示文本
text: "要显示的文本", // 如果不显示动画,则显示传入的文本
// time: 2000, // 可以为空,如果不为空,则设置多少毫秒之后关闭遮罩层
});
info.show(); // 开启遮罩层
// info.disappear(); // 关闭遮罩层
</script>
注:这个demo并未考虑移动端的兼容性,以及有些浏览器不支持ES6的类等情况。