检查是否是用户第一次访问

Pac*_*cky 1 jquery

不知道怎么做,但我想做的是运行一个简单的 jquery 动画,比如

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

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

Mic*_*ael 5

首先,您需要为“获取”、“设置”和“删除”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;';}
Run Code Online (Sandbox Code Playgroud)

接下来,在您的文档就绪函数中,您需要检查 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);
    }
});
Run Code Online (Sandbox Code Playgroud)

现在,如果你想以某种方式重置代码(比如为了测试目的来模仿某人的第一次),只需在开发人员的窗格中打开控制台(Chrome 中的 Ctrl+Shift+J 或 F12)并输入以下内容并按 [进入]

delCookie('firsttime');
Run Code Online (Sandbox Code Playgroud)