JS公告弹窗Cookie记录每天弹出次数

流氓凡 资源分享 2019-10-28 5.29 K 1

原生JS实现公告弹窗效果,设置cookie用来设置每天弹出次数,最近看一些群里很多人再需要这个,网上的代码都太复杂了

核心代码都在js里面,上面铺的网页样式太好看了(tai chou le) 不建议模仿

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>定时公告</title>
<style>
#box{
width: 700px;
height: 500px;
background: #fff;
box-shadow: 0 0 10px #ddd;
border-radius: 10px;
position: absolute;
left: 25%;
top: 20px;
text-align: center;
display: none;
}
#content{
width: 100px;
height: 100px;
margin:0 auto;
}
</style>
</head>
<body bgcolor="#eee">
<div id="content">
<span>这是一个每天只显示一次的公告Demo</span>
</div>
<div id="box">
<h2>公告</h2>
<p>我是一个公告信息</p>
<div class="ann">
<button onclick="iNow();">我知道了</button>
<button onclick="outDay();">今日不再弹出</button>
</div>
</div>
</body>
<script>
var box=document.getElementById("box");
//设置开关
var kg=getCookie("gg") == ""? "block": getCookie("gg");
//显示公告
box.style.display=kg;
//点击关闭公告
function iNow(){
box.style.display="none";
}
//点击今日不再弹出
function outDay(){
//设置cookie,时间为1天后失效(即每天弹出一次)
setCookie("gg", "none", 1);
box.style.display="none";
}

//存入cookie
var setCookie = function(c_name, value, expiredays) {
var exdate = new Date()
exdate.setDate(exdate.getDate() + expiredays)
cookieVal = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
document.cookie = cookieVal;
}

//获取cookie
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=")
if (c_start != -1) {
c_start = c_start + c_name.length + 1
c_end = document.cookie.indexOf(";", c_start)
if (c_end == -1) c_end = document.cookie.length
return unescape(document.cookie.substring(c_start, c_end))
}
}
return ""
}
</script>
</html>


评论

精彩评论