localStorage SET for a day

问题描述 投票:1回答:1

我需要弹出一个弹出窗口。它将每天更新,因此,如果用户访问网站(新用户,甚至以前访问过的用户),则弹出窗口需要每天显示页面加载情况,但是如果用户单击该通知,则需要保留该弹出窗口隐藏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);
javascript modal-dialog popup
1个回答
0
投票
我会给每个模态一个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(); }

© www.soinside.com 2019 - 2024. All rights reserved.