手机网页上时常要使用toast来弹出一下错误信息或提醒。开源上有一些很好的toast组件,例如jquery.toaster、toastr等等。但是他们的大小太大了,对于比较简单的页面,感觉有点得不偿失。
下面介绍一种利用css动画来实现的toast
HTML:
<div class="toast-wrap">
<span class="toast-msg"></span>
</div>
CSS
.toast-wrap{
opacity: 0;
position: fixed;
bottom: 10%;
color: #fff;
width: 100%;
text-align: center;
}
.toast-msg{
background-color: rgba(0,0,0,0.7);
padding: 2px 5px;
border-radius: 5px;
}
.toastAnimate{
animation: toastKF 2s;
}
@keyframes toastKF{
0% {opacity: 0;}
25% {opacity: 1; z-index: 9999}
50% {opacity: 1; z-index: 9999}
75% {opacity: 1; z-index: 9999}
100% {opacity: 0; z-index: 0}
}
javaScript
function toast(msg){
setTimeout(function(){
document.getElementsByClassName('toast-wrap')[0].getElementsByClassName('toast-msg')[0].innerHTML=msg;
var toastTag = document.getElementsByClassName('toast-wrap')[0];
toastTag.className = toastTag.className.replace('toastAnimate','');
setTimeout(function(){
toastTag.className = toastTag.className + ' toastAnimate';
}, 100);
},500);
}
使用方法:
toast('Hi, darling');