首先写一个函数来实现弹出框的功能
function myAlert(text, time) {
if (!document.getElementById('alertBg')) {
let _time = time || 1000;
let parent = document.createElement('div');
parent.setAttribute('id', 'alertBg');
let child = document.createElement('p');
child.setAttribute('class', 'text');
let _text = document.createTextNode(text);
child.appendChild(_text);
parent.appendChild(child);
document.body.appendChild(parent);
setTimeout(function () {
document.body.removeChild(parent);
}, _time)
};
}
然后写css样式
/*弹出提示框*/
#alertBg {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
z-index: 1113;
display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -moz-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
-moz-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
-moz-align-items: center;
align-items: center;
transform: all 0.3 linear;
}
#alertBg .text {
padding: 0.3rem;
border-radius: 5px;
background-color: rgba(0, 0, 0, .7);
color: #fff;
text-align: center;
text-overflow: ellipsis;
font-size: 0.5rem;
}
关于css的字体大小还有颜色,弹出框的大小都可以根据需求自行设置
需要使用的时候直接写myAlert("弹框内容");
文章来源: 原生实现小黑框toast