首先,您需要定义一些简单的 javascript 来“获取”、“设置”和“删除”cookie。我使用以下 3 个函数,将其复制并粘贴到我的下一个项目中,因此解释一切正在做什么超出了本答案的范围,除了设置Cookie设置一个新的cookie,获取Cookie根据键检索 cookie 的值,并且删除Cookie删除给定的 cookie。
function setCookie(c_name,value,exdays){var exdate=new Date();exdate.setDate(exdate.getDate() + exdays);var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());document.cookie=c_name + "=" + c_value;}
function getCookie(c_name){var c_value = document.cookie;var c_start = c_value.indexOf(" " + c_name + "=");if (c_start == -1){c_start = c_value.indexOf(c_name + "=");}if (c_start == -1){c_value = null;}else{c_start = c_value.indexOf("=", c_start) + 1;var c_end = c_value.indexOf(";", c_start);if (c_end == -1){c_end = c_value.length;}c_value = unescape(c_value.substring(c_start,c_end));}return c_value;}
function delCookie(name){document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';}
接下来,在文档就绪函数中,您需要检查 cookie 是否已存在:
$(document).ready(function(){
//Checks if the cookie already exists
if (!getCookie('firsttime')){
//Runs the code because the cookie doesn't exist and it's the user's first time
$(".intro").eq(0).delay(800).animate({opacity: 0}, 1000, function() {
$(this).remove();
});
//Set's the cookie to true so there is a value and the code shouldn't run again.
setCookie('firsttime',true);
}
});
现在,如果您想以某种方式重置代码(例如出于测试目的模仿某人的第一次),只需在开发人员窗格中打开控制台(Chrome 中的 Ctrl+Shift+J 或 F12)并输入以下内容并按 [进入]
delCookie('firsttime');