手机网页上时常要使用toast来弹出一下错误信息或提醒。开源上有一些很好的toast组件,例如jquery.toaster、toastr等等。但是他们的大小太大了,对于比较简单的页面,感觉有点得不偿失。
    下面介绍一种利用css动画来实现的toast
    HTML:

    1. <div class="toast-wrap">
    2. <span class="toast-msg"></span>
    3. </div>

    CSS

    1. .toast-wrap{
    2. opacity: 0;
    3. position: fixed;
    4. bottom: 10%;
    5. color: #fff;
    6. width: 100%;
    7. text-align: center;
    8. }
    9. .toast-msg{
    10. background-color: rgba(0,0,0,0.7);
    11. padding: 2px 5px;
    12. border-radius: 5px;
    13. }
    14. .toastAnimate{
    15. animation: toastKF 2s;
    16. }
    17. @keyframes toastKF{
    18. 0% {opacity: 0;}
    19. 25% {opacity: 1; z-index: 9999}
    20. 50% {opacity: 1; z-index: 9999}
    21. 75% {opacity: 1; z-index: 9999}
    22. 100% {opacity: 0; z-index: 0}
    23. }

    javaScript

    1. function toast(msg){
    2. setTimeout(function(){
    3. document.getElementsByClassName('toast-wrap')[0].getElementsByClassName('toast-msg')[0].innerHTML=msg;
    4. var toastTag = document.getElementsByClassName('toast-wrap')[0];
    5. toastTag.className = toastTag.className.replace('toastAnimate','');
    6. setTimeout(function(){
    7. toastTag.className = toastTag.className + ' toastAnimate';
    8. }, 100);
    9. },500);
    10. }

    使用方法:

    1. toast('Hi, darling');