1.css部分
/* 弹框 */
.npm-com-toast {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: table;
z-index: 100;
line-height: 1;
}
.npm-com-toast .mask {
display: table-cell;
vertical-align: middle;
text-align: center;
animation: npm-com-toast-mask-animation 0.3s forwards;
}
.npm-com-toast .mask .box {
display: inline-block;
box-sizing: border-box;
padding: 10px 15px;
min-width: 120px;
max-width: 200px;
min-height: 40px;
border-radius: 4px;
background: rgba(0, 0, 0, 0.65);
color: #FFF;
font-size: 14px;
line-height: 20px;
animation: npm-com-toast-mask-box-animation 0.3s forwards;
}
.npm-com-toast .mask .box .html {
display: inline-block;
text-align: center;
}
@keyframes npm-com-toast-mask-box-animation {
0% {
transform: scale(0);
}
100% {
transform: scale(1);
}
}
@keyframes npm-com-toast-mask-animation {
0% {
background: rgba(0, 0, 0, 0);
}
100% {
background: rgba(0, 0, 0, 0.1);
}
}
2.主要代码
class Toast {
constructor(options = {}) {
this.options = Object.assign({
msg: '',
duration: 3000,
timeout: null,
resolve: null,
isShow: true,
}, options);
this.elements = {
spanTemp: null,
}
this.getDuration();
}
getDuration() {
this.initElement();
this.options.timeout = setTimeout(()=>{
this.options.isShow = false;
this.getIsShow();
}, this.options.duration);
}
initElement () {
let spanTemp = document.createElement('div');
spanTemp.className = 'npm-com-toast';
let innerHtml = `
<div class="mask">
<div class="box">
<div class="html">${this.options.msg}</div>
</div>
</div>`;
spanTemp.innerHTML = innerHtml;
this.elements.spanTemp = spanTemp
window.document.body.appendChild(spanTemp);
// 关闭弹框
this.closed();
// 阻止默认事件
let box = document.getElementsByClassName('box')[0]
box.onclick = (e)=> {
e.stopPropagation();
}
}
getIsShow() {
if (this.options.isShow) {
this.elements.spanTemp.style.display = "block";
} else {
this.elements.spanTemp.style.display = "none";
}
}
// 关闭弹框
closed () {
this.options.isShow = !this.options.isShow;
this.elements.spanTemp.onclick = ()=> {
this.getIsShow();
clearTimeout(this.options.timeout);
this.options.timeout = null;
}
}
}
export default Toast;
3.使用方式
const Toast = require('./toast.js');
// 或
// import Toast from './toast.js';
new Toast({
msg: '成功吗?',
duration: 6000,
});
4.补充,在vue3.0项目里全局引入,在main.ts,里加入代码;
import Toast from '@/utils/toast';
// 全局toast
app.config.globalProperties.$toast = (data: any) => {
return new Toast({
msg: data.msg,
duration: data.duration,
});
};
页面使用
this.$toast({
msg: '引入成功~',
duration: 1500,
});