繁体   English   中英

jQuery:在我的网站上显示2秒钟后显示div,但仅显示一次,而不是每次刷新页面时或进入其他页面时显示

[英]jQuery: Show div after 2 seconds on my website, but only once and not every time the page is refreshed or when entering a different page

我有一个带有博客的网站。

每当输入它时,我都希望显示一个弹出div。 (这部分很简单- 使用jQuery在5秒钟内显示div

我希望它运行一次,也许是会话或IP,我将解释:

当用户打开博客页面时,两秒钟后,他将看到弹出窗口。 然后他可以单击X按钮将其隐藏,然后继续浏览博客,输入新页面,而不会再次显示该按钮。

那只能从前端做吗? (使用JS / jQuery)?

我不确定是要在每个会话中显示一次还是只向访问的任何用户显示一次(下次访问就不会显示,即使是第二天也是如此)。

如果只是一次,那么您可以将标志存储在localStorage 如果每个会话一次,则可以将标志存储在sessionStorage 两者都得到了很好的支持

这是一个localStorage示例; sessionStorage完全相同,除了您使用sessionStorage而不是localStorage

if (!localStorage.getItem("shown-popup")) {
    // We haven't shown it yet
    setTimeout(function() {
        // ----show the div here ----

        // Flag we've shown it (you might do this only when they click the [x])
        localStorage.setItem("shown-popup", "yes");
    }, 2000);
}

请注意,本地存储中的项目是字符串。

要允许少数没有本地存储或禁用了本地存储(私有浏览等)的用户,请将支票和套票包装在try/catch

var needToShowPopup = true;
try {
    needToShowPopup = !localStorage.getItem("shown-popup");
} catch (e) {
}
if (needToShowPopup) {
    // We haven't shown it yet
    setTimeout(function() {
        // ----show the div here ----

        // Flag we've shown it (you might do this only when they click the [x])
        try {
            localStorage.setItem("shown-popup", "yes");
        } catch (e) {
        }
    }, 2000);
}

您可以从客户端使用Cookies。 请参阅如何使用jQuery设置/取消设置cookie? 如何做到这一点。

您可以在localstorage / sessionstorage中标记一个true或false。 如果是第一次,请检查:

if (localStorage.getItem('divAlreadyShown') === 'true') { //don't show the DIV } else { //show the DIV and mark the 'divAlreadyShown' as false for next time hiding localStorage.setItem('divAlreadyShown', 'true'); }

注意: 如果要针对每个浏览器会话执行此活动,则可以将localStorage更改为sessionStorage。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM