要有遥不可及的梦想,也要有脚踏实地的本事。----------- Grapefruit.Banuit Gang(香柚帮)
js实现自定义的一个吐司,很简单,直接上代码:
一 、 首先写布局和样式
html
<div class="toast_box">
<p id="toast"></p>
</div>
css
.toast_box {
width: 100%;
position: absolute;
bottom: 50px;
justify-content: center;
display: none;
}
.toast_box p {
box-sizing: border-box;
padding: 10px 20px;
max-width: 72%;
width: max-content;
background: #000;
color: #FFF;
font-size: 16px;
text-align: center;
border-radius: 6px;
opacity: 0.8;
}
二、封装吐司的方法
function toast(text, time) {
var toast = document.getElementById('toast');
var toast_box = document.getElementsByClassName('toast_box')[0];
toast.innerHTML = text;
toast_box.style.display = 'flex';
setTimeout(() => {
toast_box.style.display = 'none';
}, time)
}
三、最后直接在需要的地方调用这个方法就行了,例如:
toast('手机号码不能为空', 3000);
自定义吐司已经完成,但只是单纯的显示和隐藏似乎是有些不太好看,用户体验会不太好,最终,柚子又加入了一些显示和隐藏的动画效果,会更好看一些,下面贴出所有代码:
<body>
<div class="toast_box">
<p id="toast"></p>
</div>
</body>
<style>
@keyframes show {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes hide {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
.toast_box {
width: 100%;
position: absolute;
bottom: 50px;
justify-content: center;
display: none;
}
.toast_box p {
box-sizing: border-box;
padding: 10px 20px;
max-width: 72%;
width: max-content;
background: #000;
color: #FFF;
font-size: 16px;
text-align: center;
border-radius: 6px;
opacity: 0.8;
}
</style>
<script>
function toast(text, time) {
var toast = document.getElementById('toast');
var toast_box = document.getElementsByClassName('toast_box')[0];
toast.innerHTML = text;
toast_box.style.animation = 'show 1.5s'
toast_box.style.display = 'flex';
setTimeout(() => {
toast_box.style.animation = 'hide 1.5s'
setTimeout(() => {
toast_box.style.display = 'none';
}, 1400)
}, time)
}
</script>
好了,就是这些了,希望能帮助到一些有需要的朋友!!!