如何使用jQuery首次访问网站时触发事件?

lim*_*oop 5 jquery fadein

嗨我希望我的网站上的导航在访问我的网站时淡入并在访问网站的其他页面时仍然存在(即不再淡入).

实现这一目标的最佳方法是告诉jQuery如果从同一个域访问,则忽略淡入效果?如果是这样,有人可以告诉我如何写这个吗?

非常感谢,加文

小智 16

没有cookie的简单方法是使用document.referrer属性.

if ( document.referrer == null || document.referrer.indexOf(window.location.hostname) < 0 ) {
// Your code here
}
Run Code Online (Sandbox Code Playgroud)

基本上我们只是检查看到用户所在的页面之前什么都没有(他们打开了一个新的浏览器窗口)或者与当前页面不在同一个域中.


Cor*_*lou 5

您无法保证用户将启用Cookie以使此解决方案正常工作.您必须首先添加一个检查,以确定在实施之前是否已启用Cookie.您可以使用这样的方法检查cookie是否已打开.

var cookieName = 'yourcookiename';
$(function() {
    checkCookie();
});

function checkCookie() {
    if (document.cookie.length > 0 && document.cookie.indexOf(cookieName + '=') != -1) {
            // do nothing, cookie already sent
    } else {
            // handle jQuery animation

            // set the cookie to show user has already visited
            document.cookie = cookieName + "=1";
    }
}
Run Code Online (Sandbox Code Playgroud)