检查是否是用户首次访问

不知道如何做到这一点,但我想要做的是运行一个简单的jquery动画,如

$(".intro").eq(0).delay(800).animate({opacity: 0}, 1000, function() { $(this).remove() }); 

但仅在用户首次访问该网站时。 因此,当用户返回主页时,在访问子页面后说他们每次都看不到动画。 可以通过创建cookie并检查它来在jquery中完成吗? 或那些线上的东西?

首先,您需要为“获取”,“设置”和“删除”Cookie定义一些简单的JavaScript。 我使用以下3个函数,我只是将其复制并粘贴到我的下一个项目中,因此解释所做的事情超出了本答案的范围,只是setCookie设置了一个新的cookie, getCookie根据键检索cookie的值,和delCookie删除给定的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;';} 

接下来,在您的文档就绪function中,您需要检查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');