原创

H5-js之自定义Toast

demo

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            body {
                background-color: red;
                width: 100%;
                height: 100%;
            }
        </style>

    </head>

    <body>
        <button onclick="showToast('test')">点我</button>
    </body>
    <script src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <script src="Toast.js"></script>
    <script type="text/javascript">
        showToast("我是测试的");
    </script>

</html>

Toast.js

var _isShowing = false; //全局
function showToast(text) {
    new Toast().show(text);
}

function Toast() {
    var _toast = null;
    var _this = this;

    var _bottom = "20%";
    var _screenWidth = document.body.clientWidth || document.body.offsetWidth || document.documentElement.clientWidth; //(实际计算时用于获取屏幕高度 兼容IE)
    var _w = 200;
    var _marginLeft = (_screenWidth - _w) >> 1;
    var _id = new Date().getTime();
    var _setTimeout;

    Toast.prototype.show = function(text) {
        if(_isShowing == true) {
            clearTimeout(_setTimeout);
            console.log(111);
            if(_toast) {
                _toast.innerText = text;
                _this.hidden(500);
            }
        } else {
            _toast = document.createElement("div");
            _toast.style.position = 'absolute';
            _toast.id = _id;
            _toast.style.width = _w + "px";
            _toast.style.textAlign = 'center';
            _toast.style.padding = '5px';
            _toast.style.borderRadius = '8px';
            _toast.style.marginLeft = _marginLeft + 'px';
            _toast.style.bottom = _bottom;
            _toast.style.backgroundColor = 'rgba(0,0,0,0.3)';
            _toast.style.color = 'white';
            _toast.innerText = text;
            document.body.appendChild(_toast);
            _isShowing = true;
            _this.hidden(1000);
        }
    }
    Toast.prototype.hidden = function(delay) {
        _setTimeout = setTimeout(function() {
            _isShowing = false;
            $('#' + _id).fadeTo("slow", 0.01, function() { //fade 透明度
                $(this).slideUp("slow", function() { //slide up 向下隐藏
                    $(this).remove(); //then remove from the DOM
                });
            });
        }, delay);
    }
}
正文到此结束
本文目录