在Bootstrap中设置一天一次的自动弹窗功能

2025-02-19T23:19:00


在 Bootstrap v5.3.0 中实现一天显示一次的自动弹窗功能,可借助 JavaScript 操作 localStoragecookie 来记录弹窗的显示状态,结合 Bootstrap 的模态框组件实现该功能。下面给出一个使用 localStorage 的示例代码:

引入必要的文件

确保在 HTML 文件中引入 Bootstrap 的 CSS 和 JavaScript 文件,同时引入 jQuery(因为示例代码使用了 jQuery 简化 DOM 操作)。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>One-time Popup</title>
</head>

<body>
    <!-- 模态框 -->
    <div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">每日提示</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    这是每天仅显示一次的弹窗提示信息。
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 引入 jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- 引入 Bootstrap JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function () {
            // 获取当前日期
            const currentDate = new Date().toLocaleDateString();
            // 从 localStorage 中获取上次显示弹窗的日期
            const lastShownDate = localStorage.getItem('lastPopupDate');

            if (lastShownDate !== currentDate) {
                // 如果上次显示日期与当前日期不同,则显示模态框
                const myModal = new bootstrap.Modal(document.getElementById('myModal'));
                myModal.show();

                // 更新 localStorage 中的日期
                localStorage.setItem('lastPopupDate', currentDate);
            }
        });
    </script>
</body>

</html>

代码解释

  1. HTML 部分

    • 创建了一个 Bootstrap 模态框,其 idmyModal,用于显示弹窗内容。
    • 模态框包含标题、主体内容和底部的关闭按钮。
  2. JavaScript 部分

    • 页面加载完成后,使用 $(document).ready() 函数执行代码。
    • 获取当前日期并转换为字符串格式。
    • localStorage 中获取上次显示弹窗的日期。
    • 若上次显示日期与当前日期不同,使用 bootstrap.Modal 实例化模态框并调用 show() 方法显示模态框。
    • 将当前日期存储到 localStorage 中,以便下次访问时进行比较。

注意事项

  • 兼容性localStorage 在现代浏览器中得到广泛支持,但在旧版本浏览器中可能存在兼容性问题。若需要支持旧版本浏览器,可考虑使用 cookie 替代。
  • 数据清除localStorage 中的数据不会自动过期,若要清除数据,可手动调用 localStorage.removeItem('lastPopupDate') 或使用 localStorage.clear() 清除所有数据。
当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »