toast

2018-11-12  本文已影响0人  web佳
/**
 * require('./lib/toast');
 * $.toast("你的文案哦");
 */
import '../../css/_common.scss';
class Toast{
    constructor(){
        this.stack=[];

        this.currentText= '';

        this.active= false;

        this.timeId=-1;
    }

    init () {
        this.$element = $('<div id="toast" class="toast-container"></div>');
        this.vw = $(window).width();
        this.appendDom();
    }

    appendDom() {
        $(document.body).append(this.$element);
    }

    show(text) {
        var me = this;
        // 如果当前toast还在显示
        if (text == this.currentText && this.active) {
            clearTimeout(this.ctimeId);
            this.ctimeId = setTimeout(function () {
                me.hide();
                if (me.stack.length) {
                    me._show();
                } else {
                    me.active = false;
                }
            }, 2000);
        } else {
            this.stack.push(text);
            if (!this.active) {
                this.active = true;
                this._show();
            }
        }
    }

    _show() {
        console.log('show')
        var me = this;
        var text = this.stack.shift();
        if (!this.$element) {
            clearInterval(me.ctimeId);
            this.init();
        }
        this.$element.show();
        //if (this.currentText != text) {
        this.currentText = text;
        var w = this.$element.html(text).width();
        this.$element.css({
            'left': (this.vw - w) / 2 + 'px',
            'opacity': 1
        });
        //}
        clearTimeout(this.ctimeId);
        this.ctimeId = setTimeout(function () {
            me.hide();
            if (me.stack.length) {
                me._show();
            } else {
                me.active = false;
            }
        }, 2000);
    }

    hide() {
        this.$element.css({
            'display': 'none',
            'opacity': 0
        });
    }

}

let toast = new Toast();

export default toast.show.bind(toast);


.toast-container {
    display: none;
    position: fixed;
    // width: 5.6rem;
    // height: 1.08rem;
    // line-height: 1.08rem;
    padding:.32rem;
    background-color: rgba(0, 0, 0, .87);
    font-family: PingFangSC-Regular;
    font-size: .32rem;
    color: rgba(255, 255, 255, 0.87);
    text-align: center;
    border-radius: .1rem;
    bottom:6.1rem;
    z-index: 99;
    -webkit-transition: opacity .6s;
    transition: opacity .6s;
    // font-weight: bold;
    /*-webkit-transform: scale(1.17);
    transform: scale(1.17);*/
}
上一篇下一篇

猜你喜欢

热点阅读