需求
第一次进入页面出现弹窗,第二次后续不再出现,如果超过某个设定时间,则继续出现。
前端使用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
使用
为静态和动态页面启动具有实时重新加载功能的开发本地服务器