原生实现小黑框toast

匿名 (未验证) 提交于 2019-12-03 00:37:01

首先写一个函数来实现弹出框的功能

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("弹框内容");

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!