使用javascript实现简单的Toast功能

Toast.js 

//暴露给外部的方法
export default function (string, time) {
  time = time || 3;
  const message = new Message(string, time);
  message.showAndHide();
}

let Message = function (message, time) {
  this.message = message;
  this.time = time;
};

Message.prototype = {
  showAndHide() {
    //为Toast创建一个包裹和一个文字容器
    const messageWR = document.createElement('div')
    const messageEl = document.createElement('p');
    //比如你的WEB_APP 的根元素的id是main
    const main = document.getElementById('main');
    messageWR.appendChild(messageEl);       
    main.appendChild(messageWR);
    messageEl.innerHTML = this.message;    
    messageWR.className='tip-message-wrap'
    messageEl.className = 'tip-message';
    //在指定的时间后移除
    setTimeout(() => {
      messageWR.remove();
    }, this.time * 1000);
  },
};

Toast.css 


.tip-message-wrap{
    position: fixed;
    text-align: center;
    top:30%;
    left: 0;
    z-index: 99999999;
    width: 100%;
}

.tip-message {
    -webkit-animation-name: fadeInAndFadeOut;
    animation-name: fadeInAndFadeOut;
    animation-duration: 2s;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
    pointer-events: none;
    margin: 0 auto;
    font-size: 13px;
    color: white;
    border-radius: 3px;
    line-height: 2;
    padding: 8px 30px;
    background-color: rgba(0,0,0,.7);
    display: inline-block;
}

@keyframes fadeInAndFadeOut {
    0% {
        opacity: 0;
    }
    40% {
        opacity: 1;
        -webkit-transform: scale(1.1);
        transform: scale(1.1);
    }
    60% {
        opacity: 1;
        -webkit-transform: scale(1.0);
        transform: scale(1.0);
    }
    80% {
        opacity: 1;
        /*transform: scale(1.1);*/
    }
    100% {
        opacity: 1;
    }
}

@-webkit-keyframes fadeInAndFadeOut {
    0% {
        opacity: 0;
    }
    40% {
        opacity: 1;
        -webkit-transform: scale(1.1);
        transform: scale(1.1);
    }
    60% {
        opacity: 1;
        -webkit-transform: scale(1.0);
        transform: scale(1.0);
    }
    80% {
        opacity: 1;
        /*transform: scale(1.1);*/
    }
    100% {
        opacity: 1;
    }
}

 

 

 

在使用的时候就可以

import Toast from 'Toast';

Toast('透!',2)

大概在两秒后隐藏

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值