首页 > 解决方案 > 模态窗口应该每天只为每位访客打开一次

问题描述

我创建了一个模态窗口,几秒钟后向网站访问者显示以通知新的东西。

此处显示的最终结果屏幕截图

这是临时示例网页

我使用的代码如下:

<div id="ex1" class="modal">
<h1 style="color:#395CC3">We need you !</h1><br>
<p>Lots of text...</p>
<div align="right"> <a href="mailto:contatti@andreadd.it" style="color: 
#395CC3; text-decoration:none">CONTATTACI !!!</a></div>
</div>

<script type="text/javascript">
setTimeout(function(event) {
  $('#ex1').modal({
    fadeDuration: 500,
    fadeDelay: 1.50,
    escapeClose: false,
  });
}, 10000);
</script>

该代码可以正常工作,但我想将此代码放在所有网站页面上。我需要如果弹出窗口显示给访问者,那么它至少在一天内不会再显示给该访问者。

你能帮我添加可以做到这一点的代码部分吗?非常感谢你!

标签: javascripthtmlcachingcookiesmodal-dialog

解决方案


您可以使用 localStorage 来存储上次显示的时间。LocalStorage w3schools

let lastShown = parseInt(localStorage.getItem('lastShown')); //EDIT: Added parseInt
let maxTime = 1000; //ms (1 second)
//if lastShown is undefined or enough time has passed
if(!lastShown | lastShown + maxTime < Date.now()) { 

  //show it 
  //store the time to check next time the page is loaded
  localStorage.setItem('lastShown', Date.now());
}

推荐阅读