js封装toast组件——常用工具函数

以下是封装的代码

/**
 * 用原生 JS 封装一个 Toast 组件
 */
var Toast = {
    // 隐藏的 setTimeOut 引用
    hideTimeOut: null,
    /**
     * 初始化
     */
    init: function () {
        var toastNode = document.createElement('section');
        toastNode.innerHTML = '<i class="iconfont icon-success"></i><i class="iconfont icon-error"></i><span class="text">111</span>';
        toastNode.id = 'toastWaka'; // 设置id,一个页面有且仅有一个Toast
        toastNode.setAttribute('class', 'toast');   // 设置类名
        toastNode.style.display = 'none';   // 设置隐藏
        document.body.appendChild(toastNode);
    },
    /**
     * 显示Toast
     * @param text 文本内容
     * @param type 类型 success error
     * @param duration 持续时间
     */
    show: function (text, type, duration) {
        // 确保上一次的 TimeOut 已被清空
        if (this.hideTimeOut) {
            clearTimeout(this.hideTimeOut);
            this.hideTimeOut = null;
            // console.error('上一次的 TimeOut 还未走完!');
            // return;
        }
        if (!text) {
            console.error('text 不能为空!');
            return;
        }
        var domToastWaka = document.getElementById('toastWaka');
        console.log('domToastWaka', domToastWaka);
        if (!domToastWaka) {
            console.error('toastWaka DOM 不存在!');
            return;
        }
        var domIconSuccess = domToastWaka.querySelector('.icon-success');   // 成功图标
        var domIconError = domToastWaka.querySelector('.icon-error');   // 错误图标
        var domToastText = domToastWaka.querySelector('.text');   // 文字
        domToastText.innerHTML = text || '';
        switch (type) {
            case 'success':
                domIconSuccess.style.display = 'inline-block';
                domIconError.style.display = 'none';
                break;
            case 'error':
                domIconSuccess.style.display = 'none';
                domIconError.style.display = 'inline-block';
                break;
            default:
                domIconSuccess.style.display = 'none';
                domIconError.style.display = 'none';
                break;
        }
        domToastWaka.style.display = 'block';
        // 不传的话默认2s
        var that = this;
        this.hideTimeOut = setTimeout(function () {
            domToastWaka.style.display = 'none';
            that.hideTimeOut = null;    // 置 TimeOut 引用为空
        }, duration || 2000);
    },
    /**
     * 隐藏 Toast
     */
    hide: function () {
        // 如果 TimeOut 存在
        if (this.hideTimeOut) {
            // 清空 TimeOut 引用
            clearTimeout(this.hideTimeOut);
            this.hideTimeOut = null;
        }
        var domToastWaka = document.getElementById('toastWaka');
        if (domToastWaka) {
            domToastWaka.style.display = 'none';
            document.body.removeChild(domToastWaka);
        }
    }
};

css样式设置

/*toast样式*/
#toastWaka {
    position: absolute;
    display: none;
    left: 50%;
    bottom: 50%;
    z-index: 99999;
    margin: 0 auto;
    -webkit-transform: translate(-50%);
    transform: translate(-50%);
    width: 120px;
    height:40px;
    line-height: 40px;
    border-radius: 5px;
    text-align: center;
    color: #fff;
    background-color: rgba(000,000,000,0.5);
}

#toastWaka .text{
    color: #fff;
    display: inline-block;
    font-size: 14px;
    position: absolute;
    top:0;
    bottom:0;
    right:0;
    left:0;
}

如何使用

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>toast</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no"/>
    <meta name="description" content="" />
    <style>
    /*toast样式*/
    #toastWaka {
        position: absolute;
        display: none;
        left: 50%;
        bottom: 50%;
        z-index: 99999;
        margin: 0 auto;
        -webkit-transform: translate(-50%);
        transform: translate(-50%);
        width: 120px;
        height:40px;
        line-height: 40px;
        border-radius: 5px;
        text-align: center;
        color: #fff;
        background-color: rgba(000,000,000,0.5);
    }

    #toastWaka .text{
        color: #fff;
        display: inline-block;
        font-size: 14px;
        position: absolute;
        top:0;
        bottom:0;
        right:0;
        left:0;
    }
    </style>
</head>
<body>
    <section id="redbag">    
        <button class="downbtn" onclick="icCopy()">复制邀请码</button>
    </section>
    <!--<script src="http://browser.umeweb.com/v6/ume/js/common/jquery.js"></script>-->
    <script src="./toast.js"></script>
    <script type="text/javascript">
        function icCopy() {
            try {
                // Now that we've selected the anchor text, execute the copy command
                var msg = '邀请码已复制' ;
                var type =  'success';
                Toast.init();
                Toast.show(msg, type, null);
                setTimeout(function () {
                    Toast.hide();
                }, 20000);
            } catch (err) {
                Toast.init();
                Toast.show('Oops, unable to copy', 'error', null);
                setTimeout(function () {
                    Toast.hide();
                }, 20000);
            }
        }
    </script>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的React封装toast组件的示例: ```jsx import React, { useState, useEffect } from 'react'; import ReactDOM from 'react-dom'; import './toast.css'; const Toast = ({ message, duration = 3000, onClose }) => { const [visible, setVisible] = useState(false); useEffect(() => { setVisible(true); const timer = setTimeout(() => { setVisible(false); onClose && onClose(); }, duration); return () => clearTimeout(timer); }, [duration, onClose]); return visible ? ( <div className="toast"> <div className="toast-message">{message}</div> </div> ) : null; }; const showToast = (message, duration = 3000, onClose) => { const div = document.createElement('div'); document.body.appendChild(div); ReactDOM.render( <Toast message={message} duration={duration} onClose={() => { ReactDOM.unmountComponentAtNode(div); onClose && onClose(); }} />, div ); }; export default showToast; ``` 这个组件包含一个`Toast`组件和一个`showToast`函数。`Toast`组件接收`message`、`duration`和`onClose`作为属性,其中`message`表示要显示的消息,`duration`表示消息显示的时间(默认为3秒),`onClose`表示关闭消息时的回调函数。 `showToast`函数用于在页面上创建一个`Toast`组件并显示消息。它接收与`Toast`组件相同的属性,还有一个可选的`onClose`回调函数,用于在消息关闭时执行其他操作。 在使用时,可以像这样调用`showToast`函数: ```jsx import React from 'react'; import showToast from './toast'; const MyComponent = () => { const handleClick = () => { showToast('Hello, world!', 2000, () => console.log('Toast closed.')); }; return ( <button onClick={handleClick}>Show Toast</button> ); }; export default MyComponent; ``` 这个示例在点击按钮时显示一个消息框,显示2秒后关闭,并在关闭时输出一条消息到控制台。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值