js实现开屏弹窗

各位上次教大家制作另一个简单的开屏弹窗,但是其中是有一点问题的。比如在刷新页面的时候开屏弹窗会再次出现,但是在现实情况中很少出现这种情况。那我们怎么做呢,这时候就需要用到我们之前学到的BOM中的临时存储了。直接展示好吧。

HTML

html 复制代码
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>点击消失的开屏弹窗</title>
</head>
<body>

    <div class="splash-screen" id="splashScreen">
        <h1>欢迎来到我的网站</h1>
        <p>点击任意地方关闭此窗口</p>
    </div>

    <div class="content">
        <h2>主内容区域</h2>
        <p>这里是网站的主要内容。</p>
    </div>

    <script src="script.js"></script>
</body>
</html>

CSS (styles.css)

html 复制代码
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
}

.splash-screen {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 9999; /* 确保在最上层 */
    transition: opacity 0.5s ease; /* 添加渐变效果 */
}

.content {
    padding: 20px;
}

JavaScript (script.js)

javascript 复制代码
// 获取弹窗元素
let splash = document.getElementById('splashScreen');

// 检查 sessionStorage 中是否已设置弹窗的显示状态
if (sessionStorage.getItem('splashScreenClosed') == '1') {
    splash.style.display = 'none'; // 如果已关闭,隐藏弹窗
} else {
    splash.style.display = 'flex'; // 否则显示弹窗
}

// 处理弹窗的点击事件
splash.addEventListener('click', function() {
    sessionStorage.setItem('splashScreenClosed', '1'); // 设置标志,表示弹窗已关闭
    splash.style.opacity = '0'; // 渐变消失
    setTimeout(() => {
        splash.style.display = 'none'; // 完全隐藏
    }, 500); // 与 CSS 中的过渡时间相同
});

ok了也是非常之简单,接下来带大家整理下整体思路

  1. HTML:

    • 创建了一个带有欢迎消息的弹窗和一个主内容区域。
  2. CSS:

    • 设置 .splash-screen 的样式,使其全屏覆盖并居中显示内容。
  3. JavaScript:

    • 使用 document.getElementById 获取弹窗元素。
    • 在页面加载时检查 sessionStorage 中的 splashScreenClosed 项:
      • 如果值为 '1',则隐藏弹窗。
      • 如果值不存在或不等于 '1',则显示弹窗。
    • 添加一个点击事件监听器,当用户点击弹窗时:
      • 将 splashScreenClosed 设置为 '1',表示弹窗已关闭。
      • 通过设置透明度并使用 setTimeout 来实现平滑的消失效果。
相关推荐
临床数据科学和人工智能兴趣组2 小时前
在R语言中, 使用 as.factor() 函数转换数值型变量
开发语言·r语言
andyweike5 小时前
php笔记
开发语言·笔记·php
Circ.6 小时前
Python 调试 Litellm 本地大模型接口:模型列表与对话接口实操踩坑记录
开发语言·python
现任明教教主~8 小时前
Thinkphp站群蜘蛛池SaaS系统YanyvSEO含多用户/积分/六大引擎计费/易支付对接
java·开发语言·spring
Zhou1411368 小时前
SpringSecurity_02_授权与高级功能
开发语言·python
码匠许师傅9 小时前
【C++三方组件】cpp-httplib:一个头文件起 HTTP 服务
开发语言·c++·http
小小小小钰儿10 小时前
1.5-Python网络编程
开发语言·网络·python·web安全·计算机·网络安全
hiahiahia12310 小时前
实现完整 Tool Dispatcher
开发语言·前端