gpt4 book ai didi

javascript - localStorage SET 仅限一天

转载 作者:行者123 更新时间:2023-11-28 03:03:06 25 4
gpt4 key购买 nike

我需要弹出一个窗口。它会每天更新,因此如果用户访问该网站(新用户甚至以前访问过的用户),则弹出窗口需要每天在页面加载时显示,但如果用户单击通知离开,则它需要保留重置前隐藏 24 小时。我已经编写了这段代码,但无法使用 localStorage 将其与上次显示的时间进行比较。

  var modal = document.querySelector(".opening-modal");
var close = document.getElementById("pageDiv");
var element = document.getElementById("pageDiv");

function popupShown() {
if (!localStorage.getItem('showPopup')) { //check if popup has already been shown, if not then proceed
localStorage.setItem('showPopup', 'true'); // Set the flag in localStorage
element.classList.add("show-modal");
}
}
function closeModal() {
element.classList.add("hide-modal");
}
window.setTimeout(popupShown, 1500);
window.addEventListener("click", closeModal);

最佳答案

我会给每个模态一个 ID(升序)并存储用户关闭的最后一个模态的 ID。这样,如果模式在 48 小时(而不是 24 小时)内没有更改,则用户不会再次显示该模式。

var popupId = 42; // This is the number that changes when the content changes
if (+localStorage.dismissedPopup !== popupId) {
// Either the user has never dismissed one of these, or it's not the most recent one
window.setTimeout(popupShown, 1500);
}
function closeModal() {
element.classList.add("hide-modal");
// Remember the ID of the most recent modal the user dismissed
localStorage.dismissedPopup = popupId;
}

如果您想从 HTML 驱动它,ID 可以来自 data-* 属性:

<div id="pageDiv" data-popup-id="42">An important update about...</div>

然后:

var popupId = +element.getAttribute("data-popup-id");
<小时/>

但是如果您希望它是基于时间的,请存储上次关闭的时间:

if (!localStorage.lastPopupDismissed ||
(Date.now() - localStorage.lastPopupDismissed) > (24 * 60 * 60 * 1000))) {
window.setTimeout(popupShown, 1500);
}
function closeModal() {
element.classList.add("hide-modal");
// Remember the ID of the most recent modal the user dismissed
localStorage.lastPopupDismissed = Date.now();
}

关于javascript - localStorage SET 仅限一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60814927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com