我希望以下代码每次访问只运行一次。如果我从主页导航到不同的页面并返回主页,我不应该再看到效果。如果我刷新页面,我应该看到效果。这是代码:
function stack(){
$('#image').animate({
width: 200,
height: 150,
top: 0,
},1500);
}
$(function(){
stack();
});
以下是我正在做的事:http://jsfiddle.net/kq5M4/
答案 0 :(得分:2)
设置一个标记已发生效果的Cookie,同时在每个跟踪最后一页的页面加载上设置一个Cookie。如果加载主页并且上次访问的页面也是主页,请再次运行该效果。
(使用https://github.com/carhartl/jquery-cookie.)
在主页上:
var lastPage = $.cookie('last_page');
if (!lastPage || lastPage == document.location.pathname)
stack();
在每个页面(包括主页)上:
$.cookie('last_page', document.location.pathname, {expires: 0}); // expires: 0 makes it a session-only cookie
您 还可以检查引荐来源,以便它们离开您的网站后再次运行。
答案 1 :(得分:1)
在页面加载时,检查document.referrer
,如果与您的域不同或为空,则执行动画。在您的网页之间导航或刷新页面将使您的网域位于document.referrer
,以便您跳过动画。
$(function(){
if (!document.referrer.match(/buybluesky.com/) || document.referrer == document.location.href) {
stack();
}
});
编辑: 似乎我错过了一些东西,但我已经编辑了代码来匹配你所有的标准。除了检查引用者是否需要显示动画之外,还检查引用者是否等于当前位置。如果他们这意味着它是一个刷新,因为你从这个页面来到这个页面。
答案 2 :(得分:1)
使用sessionStorage&存储最后一页:
var visited = sessionStorage.getItem('visit');
if (visited == null || document.location.href == sessionStorage.getItem('lastPage')) {
stack();
sessionStorage.setItem('visit', 1);
}
sessionStorage.setItem('lastPage', document.location.href);