检查是否是用户第一次访问 [英] Check if it is users first visit
问题描述
不确定如何执行此操作,但是我一直想做的是运行一个简单的jquery动画,例如
Not sure how to do this, but what I was looking to do is run a simple jquery animation such as
$(".intro").eq(0).delay(800).animate({opacity: 0}, 1000, function() {
$(this).remove()
});
,但仅当用户首次访问该网站时.因此,当用户返回首页时,访问子页面后说,他们每次都看不到动画.可以通过创建cookie并检查它在jquery中完成吗?或在那些线上的东西?
but only when the user first visits the site. So when the user goes back to the homepage say after visiting a sub page they dont see the animation every time. Can this be done in jquery by creating a cookie and checking it? or something on those lines?
推荐答案
首先,您需要为获取",设置"和删除" cookie定义一些简单的javascript.我使用了以下3个函数,它们只是复制并粘贴到我的下一个项目中,因此,除了 setCookie 设置新的Cookie getCookie 根据键检索cookie的值,而 delCookie 删除给定的cookie.
First, you need to define some simple javascript for "getting", "setting" and "deleting" cookies. I use the following 3 functions that I just copy and paste to my next project, so explaining what everything is doing is beyond the scope of this answer except that setCookie sets a new cookie, getCookie retrieves the value of a cookie based on a key, and delCookie deletes a given 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是否已经存在:
Next, in your document ready function, you would want to check if a cookie already exists:
$(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),然后输入以下内容然后按[ENTER]
Now, if you want to reset the code somehow (say for testing purposes to imitate someone's first time), simply open up the console in the developer's pane (Ctrl+Shift+J or F12 in Chrome) and type in the following and press [ENTER]
delCookie('firsttime');
这篇关于检查是否是用户第一次访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!