【问题标题】:How do I display a modal only once per hour for each user?如何为每个用户每小时仅显示一次模式?
【发布时间】:2022-02-12 01:02:13
【问题描述】:

我有一个显示索引加载模型的网站。目前,它会在您每次进入索引页面时加载。这对网站的用户来说非常烦人。我想知道每个用户是否只能每小时显示一次?该网站位于 wikiraces.com

<!-- MODAL FOR NEWS-->
<div id="div1" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
    </div>
    <!-- Modal content -->
<div class="modal-content">
  <div class="modal-header">
    <span class="close">&times;</span>
    <h2>New Features/Updates</h2>
  </div>
  <div class="modal-body">
   <h4> <p>The Fewest Clicks Game is Back!</p> </h4> 
    <p>
    It was down for maintanece for 14 hours but finally it is back
    </p> 
  
    <h4> The Multiplayer host random page is here! </h4> 
    <p>
     You can now play multiplayer without the hassle of chosing your own start!
      <br> 
      <br>
      <a href="/html/about.html"> <b> Report bugs </b></a>

    </p>
  </div>
  <div class="modal-footer">
   <h5> Enjoy, and remember to share this website with your friends! </h5>
  </div>
</div>
  </div>

</div> 

<script>
  // Get the modal
var modal = document.getElementById("div1");

// Get the <span> element that closes the modal
var spanTimed = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
window.onload = function() {
  modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
spanTimed.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none"; 
  }
}

</script>

【问题讨论】:

  • 存储一个时间戳(本地存储或数据库)并与当前时间进行比较。

标签: javascript html jquery modal-dialog


【解决方案1】:

我们可以将上次打开模态的时间存储在localStorage 中,并且每次用户访问该站点时,我们都可以检查存储的时间与当前时间之间的差异。如果花费的时间大于一小时,则显示模态。

window.addEventListener('load', () => {
  let time = localStorage.getItem('time');
  if ( time === null ) {
    localStorage.setItem('time', new Date());
    modal.style.display = "block";
    return;
  }
  
  let current = new Date();
  if ( current - time >= 60 * 60 * 1000 ) {
    modal.style.display = "block";
  }
 
})

【讨论】:

  • 我是否需要保留 window.onload 函数,因为我用这个替换了它并且它没有弹出但当然这可能意味着它可以工作但我实际上不确定。
  • 它应该是第一次显示模态。修改后的代码可以分享一下吗?
  • 没关系,我在虚拟浏览器中对其进行了测试,非常感谢!
  • 很高兴我能帮上忙 :)
  • 它可以工作,但它不再可用。我不知道为什么。这是源代码。我没有改变任何感觉它一直在工作的东西(也复制视图源)视图源:wikiruns.com
猜你喜欢
  • 2020-01-11
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
相关资源
最近更新 更多