cookie设置今日不提醒功能
需求:为了实现 退出页面时 【启动今日不提醒】的功能。采用纯js、cookie来实现。
/****今日不提醒 start *****/ var userid = <%=UserId %>; var cookieName = "tcdyh" + userid;//缓存名称 if(cookies.getCookie(cookieName)==undefined) {//判断是否有缓存--没缓存就执行弹窗 /*****退出弹窗 start*******/ if (location.href.indexOf('#') < 0) { history.pushState("", "", location.href + "#new"); //配合popstate事件使用 } // 设置退出弹窗 setTimeout(function () { window.addEventListener("popstate", function () { $('#dyh').show(); //弹窗外框 $('.amusing').show(); $('.focus').show(); //二维码 $('.mask').hide(); $('.wrap_iframe').hide(); $('.sidebar').hide(300); }); }, 2000); /****退出弹窗 end*********/ } //根据选中框来添加和移除缓存 $(":checkbox").on("change",function(){ if ($(this)[0].checked) { cookies.setCookie(cookieName,userid); } else { cookies.removeCookie(cookieName); } }); /****今日不提醒 end *****/
/*********JS操作cookies方法! ***************/ var cookies = { "setCookie": function (name, value) {//设置截止到当天23:59:59 var curDate = new Date(); //当前时间戳 var curTamp = curDate.getTime(); //当前日期 var curDay = curDate.toLocaleDateString(); var curWeeHours = 0; curWeeHours = new Date(curDay).getTime() - 1; //当日已经过去的时间(毫秒) var passedTamp = curTamp - curWeeHours; //当日剩余时间 var leftTamp = 24 * 60 * 60 * 1000 - passedTamp; var leftTime = new Date(); leftTime.setTime(leftTamp + curTamp); //创建cookie document.cookie = name + "=" + value + ";expires=" + leftTime.toGMTString() + ";path=/"; }, "getCookie": function (name) { //name 为想要取到的键值的键名 var reg = /\s/g; var result = document.cookie.replace(reg, ""); var resultArr = result.split(";"); for (var i = 0; i < resultArr.length; i++) { var nameArr = resultArr[i].split("="); if (nameArr[0] == name) { return nameArr[1]; } } }, "removeCookie": function (name) { //name为想要删除的Cookie的键名 var oDate = new Date(); //时间对象 oDate.setDate(new Date().getDate() - 1); document.cookie = name + "=123;expires=" + oDate + ";path=/"; } }; /*********JS操作cookies方法! end ***************/