之前用jq封装了一次toast提示方法,
https://blog.csdn.net/tuzi007a/article/details/121273822
但是用了一段时间后,发现有一定的缺点,比如
- 需要引入jquery才能使用该方法,
- 缺少动画
- 容易让用户误解,如果前后toast提示内容差不多,用户都看不出来有新的taost提示
- 。。。
鉴于这些因素,今天就重新用原生js进行封装,
增加了淡出动画,改善了用户体验,原生js封装,使用也更加方便。
至于为啥不用像antd这样的ui组件,
主要是因为不想搞这么复杂,另外就是业务要求不同。
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
button {
margin-left: 100px;
}
#toast__wrap {
position: fixed;
z-index: 999;
top: 100px;
left: 100px;
width: 200px;
}
.toast {
width: 100%;
background-color: rgba(0 0 0 / .8);
box-sizing: border-box;
padding: 2px 5px;
border-radius: 12px;
font-size: 16px;
color: #fff;
text-align: center;
margin-bottom: 5px;
margin-top: 0;
opacity: 1;
}
.toast-move {
margin-top: -25px;
opacity: 0;
transition: margin-top .2s linear, opacity .2s linear;
}
</style>
</head>
<body>
<button> click show toast </button>
<script>
var btn = document.querySelector('button')
btn.onclick = function () {
showToast('测试toast提示')
}
// 重新封装toast提示
function showToast(text) {
var transitionTime = 200 // toast消失用时200ms
var existTime = 1500 // 一条toast存在的时间,1500ms后自动消失
var totalTime = transitionTime + existTime // 所有操作都结束的时间
// toast提示的外层盒子
var wrap = document.querySelector('#toast__wrap')
// 如果外层盒子不存在,就创建一个新的外层盒子
if(!wrap) {
var _wrap = document.createElement('div')
_wrap.setAttribute('id', 'toast__wrap')
document.body.appendChild(_wrap)
wrap = document.querySelector('#toast__wrap')
}
// 创建toast盒子
var _div = document.createElement('div')
_div.setAttribute('class', 'toast')
wrap.appendChild(_div)
_div.innerHTML = text
var toasts = document.querySelectorAll('.toast')
// 如果toast同时存在两条,那么最初的那条,要去掉
if (toasts.length === 2) {
toasts[0].classList.add('toast-move')
var outTimer = null
// toast提示执行transition动画后,就删除
outTimer = setTimeout(function() {
toasts[0].remove()
clearTimeout(outTimer)
}, transitionTime)
} else if (toasts.length > 2) {
// 如果快速点击,导致同时存在的toast提示有很多,那么就把旧的toast都删除
// 目的是永远只保留最新的那一条toast提示
toasts[0].remove()
toasts[1].remove()
}
var timer1 = null
var timer2 = null
// 一条toast提示最多存在1500ms,
// 在没有任何操作的情况下,1500ms后toast会自动开始消失
timer1 = setTimeout(function () {
toasts[toasts.length - 1].classList.add('toast-move')
clearTimeout(timer1)
}, existTime)
// 等到所有动画和操作都结束了,检查当前还有没有toast提示存在
// 如果有,就删除,如果没有,连外层盒子也跟着删除
// 同时,把变量都设为null,防止内存泄漏
timer2 = setTimeout(function () {
toasts[toasts.length - 1].remove()
wrap.childNodes.length === 0 && wrap.remove()
clearTimeout(timer2)
wrap = null
toasts = null
}, totalTime)
}
</script>
</body>
</html>