You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Div仅在周一至周三显示并添加关闭隐藏按钮

实现仅周一至周三显示的可关闭消息框

完整代码实现

下面是整合了HTML、CSS和JavaScript的完整方案,包含日期判断、关闭功能及本地存储记忆:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weekly Banner</title>
    <style>
        .header {
            position: relative;
            width: 100%;
        }
        .banner {
            display: none; /* 默认隐藏,由JS控制显示 */
            background-color: #f0f8ff;
            padding: 1rem;
            border: 1px solid #b3d9ff;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 1rem;
        }
        .close-button {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #666;
            padding: 0 0.5rem;
        }
        .close-button:hover {
            color: #000;
        }
    </style>
</head>
<body>
    <div class="header">
        <div id="banner" class="banner" role="alert">
            <p>Attend the Chamber of Commerce meet and greet 🤝 on Wednesday at 7:00 p.m.</p>
            <button id="closeBanner" class="close-button" aria-label="Close">×</button>
        </div>
    </div>

    <script>
        const banner = document.getElementById('banner');
        const closeBtn = document.getElementById('closeBanner');
        const today = new Date().getDay(); // 0=周日, 1=周一, 2=周二, 3=周三
        const hasClosed = localStorage.getItem('bannerClosed');

        // 检查是否是周一至周三,且未关闭过
        if ([1,2,3].includes(today) && !hasClosed) {
            banner.style.display = 'flex';
        }

        // 关闭按钮逻辑
        closeBtn.addEventListener('click', () => {
            banner.style.display = 'none';
            localStorage.setItem('bannerClosed', 'true');
            // 当天结束后清除存储,第二天符合条件时重新显示
            const midnight = new Date();
            midnight.setHours(24, 0, 0, 0);
            setTimeout(() => {
                localStorage.removeItem('bannerClosed');
            }, midnight - new Date());
        });
    </script>
</body>
</html>

关键功能说明

  • 日期判断:通过new Date().getDay()获取当前星期数,仅当值为1(周一)、2(周二)、3(周三)时显示消息框。
  • 关闭记忆:使用localStorage存储用户关闭状态,避免刷新页面后消息框重复弹出;同时设置定时清除存储,确保第二天符合条件时消息框会再次出现。
  • 样式优化:默认隐藏消息框,通过JavaScript控制显示;关闭按钮添加hover效果,提升交互体验。

内容的提问来源于stack exchange,提问作者Mak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 20:52:06