使用cookie控制首次进入页面出现弹窗,后续不再出现

需求

第一次进入页面出现弹窗,第二次后续不再出现,如果超过某个设定时间,则继续出现。
前端使用cookie进行配置该需求
cookie的使用教程:https://www.runoob.com/js/js-cookies.html

解决方法

创建一个js文件:tanchuang.js
对需要处理的页面在进入页面触发即可;

// 设置cookie
function setCookie(cname,cvalue,exdays){
    var d = new Date();
    d.setTime(d.getTime()+(exdays*24*60*60*1000));
    var expires = "expires="+d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;
}

// 获取cookie
function getCookie(cname){
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name)==0) { return c.substring(name.length,c.length); }
    }
    return "";
}

// 检查是否有该cookie
function checkCookie(){
    var use=getCookie("username");
    if (use != ""){ // 不为空处理
        document.getElementById('popup').style.display = 'none'
    }
    else {// 为空处理
        document.getElementById('popup').style.display = 'block'
    }
}

html页面(引用js测试即可)
(第一次点击可以出现弹窗,关闭后第二次点击则没有弹窗的出现)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .popup{
            width: 300px;
            height: 300px;
            background-color: red;
            margin: 50px auto;
            display: none;
            text-align: center;
            color: #fff;
        }
    </style>
</head>
<body>
    <div class="ceshi" onclick="checkCookie()">欢迎进入测试弹窗页面</div>
    <div class="popup" id="popup">我是弹窗</div>
    <script type="text/javascript" src="./tanchuang.js"></script>
    <script type="text/javascript">
        var guanbi = document.getElementById('popup')
        guanbi.onclick=function(){
            console.log('1');
            guanbi.style.display = 'none'
            setCookie('username',true,1)
        }
    </script>
</body>
</html>

注意:本地调用cookie可能不生效,一般需要端口服务的调用

使用xscode可以安装该服务Live Server使用
为静态和动态页面启动具有实时重新加载功能的开发本地服务器

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值