如果用户是第一次访问网站,我希望在我的网站上执行一些动画效果。我已经找到了使用localStorage
来判断是否为“首次访问者”的代码,但还不清楚如何实现。
如果用户是第一次访问网站,我希望在我的网站上执行一些动画效果。我已经找到了使用localStorage
来判断是否为“首次访问者”的代码,但还不清楚如何实现。
您可以使用cookie
或localStorage
。假设您有以下HTML代码:
<div id="first">
Welcome Visitor
</div>
<p>This is my website.</p>
#first {
display: none;
}
然后我们进行首次检查。如果是第一次,我们会展示该元素(并可能对其执行一些动画):
// this is the first time
if (! localStorage.noFirstVisit) {
// show the element
// and do the animation you want
document.getElementById('first').style.display = 'block';
// check this flag for escaping this if block next time
localStorage.noFirstVisit = "1";
}
true
而不是 "1"
。 - Niki Romagnolidisplay
设置为block
来使内容出现。none
的相反值是initial
! - Martinif(document.referrer.indexOf("yourdomain.com")==-1) {
//first pageview of the session
}
如果页面引用信息(document.referrer)丢失了,您还可以设置一个cookie。
window.location.hostname
可以用于: if(document.referrer.indexOf(window.location.hostname)==-1) {}
- sebastian.ifunction 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;
}
获取Cookie的值
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;
}
假设您的意思是在此窗口中查看的第一页:
if (location.referrer == location.href)
{
// the page was opened in a new window or tab and accessed directly
}
else if (location.referrer.indexOf(location.hostname) == -1)
{
// The page before this one was not a page on this site
}
在我看来,我认为最好使用数据库来跟踪这些操作。 使用本地存储或者cookie是特定于浏览器的。一旦用户更换浏览器,该功能就必须重新开始。然而,使用数据库可以实现持久性。 以下是你可以在数据库中做的事情。