调用:
xwToast({
message:"成功提示", //提示文字
time:30000, //关闭时间 设置默认3秒
background:'#07c060', //背景颜色 设置默认red
color:"#fff", //文字颜色 默认#fff
showClose:true, //是否显示关闭按钮
autoClose:false, //是否自动关闭 showClose为false则默认为true
},res=>{ //关闭回调 返回message值
console.log(res);
})
.js
function xwCreate(){
let div = document.createElement('div');
div.className = 'xw_style'
document.querySelector('body').appendChild(div)
}
function xwToast({...data},reslove) {
document.querySelector('.xw_style')==null?xwCreate():'';
let div = document.createElement('div');
if(data.message){
div.innerText = data.message
}else{
throw(new Error('Missing parameter: message!'))
}
if(data.message.length>20){
throw(new Error('Message text is too long to display!'))
}
div.className = 'xw_style_list';
let xw_style_id = 'xw_style_id_'+ new Date().getTime();
div.id = xw_style_id;
div.style.background = (data.background && data.message&&data.message.length<=20)?data.background:''
div.style.color = data.color?data.color:''
document.querySelector('.xw_style').appendChild(div)
let idList = [];
data.showClose?xwDel(xw_style_id,data.message,(message,id)=>{
reslove?reslove(data.message):''
id?idList.push(id):''
}):''
setTimeout(() => {
if(data.autoClose || !data.showClose || data.time){
document.querySelector('#'+xw_style_id)?document.querySelector('#'+xw_style_id).remove():''
}
if(idList.indexOf(xw_style_id) == -1){
reslove?reslove(data.message):''
}
}, data.time?data.time:3000);
}
function xwDel(id,message,reslove) {
let div = document.createElement('div');
div.className = 'xw_style_des'
div.innerText = '×';
div.onclick = function (){
document.querySelector('#'+id).remove()
reslove(message,id)
};
document.querySelector('#'+id).appendChild(div)
}
.css
.xw_style{
position: fixed;
top: 0;
left: 0;
right: 0;
width: 350px;
height: auto;
margin: 0 auto;
}
.xw_style_list{
width: 100%;
height: 50px;
color: #fff;
background: red;
line-height: 50px;
padding: 0 20px;
box-sizing: border-box;
white-space:nowrap;
overflow:hidden;
text-overflow:ellipsis;
animation-name: xwhd;
animation-duration: 1s;
animation-fill-mode: forwards;
font-size: 14px;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: space-between;
position: relative;
}
.xw_style_des{
position: absolute;
right: 20px;
font-size: 20px;
cursor:pointer;
}
@keyframes xwhd{ /* 定义关键帧 hd动画名 */
0%{
opacity: 0;
margin-top: 0px;
}
25%{
}
100%{
opacity:1;
margin-top: 20px;
}
}