简体   繁体   English

加载时弹出模式的延迟

[英]Delay for popup modal on load

I like this script because it's simple, but am new to JS to I'm not sure how to add a 5 second delay before showing the "welcome" greeting. 我喜欢这个脚本,因为它很简单,但是对于JS来说是新手,我不确定如何在显示“欢迎”问候语之前添加5秒的延迟。

var hasSeenGreeting = localStorage.getItem("greeting");

if(!hasSeenGreeting){
       document.getElementById("welcome").style.display = "block";
       localStorage.setItem("greeting", "true");
}

document.querySelector(".button").addEventListener("click", function(){
  localStorage.removeItem("greeting", "true");
});

You can use setTimeout(). 您可以使用setTimeout()。 Here is a reference link . 这是参考链接

setTimout(function() {
    document.getElementById("welcome").style.display = "block";
    localStorage.setItem("greeting", "true");
}, 5000); // 5 second delay in ms.

In the code above, I'm passing an anonymous function to the setTimeout call. 在上面的代码中,我将一个匿名函数传递给setTimeout调用。 Inside of that function I'm executing your code for setting the display property of your welcome div - along with setting the localStorage value. 在该函数内部,我正在执行您的代码来设置您的div的display属性-以及设置localStorage值。

Another way to accomplish this is to put these calls in their own function and then call it in the setTimeout. 完成此操作的另一种方法是将这些调用放在自己的函数中,然后在setTimeout中调用它。 Example: 例:

var showDiv = function() {
  document.getElementById("welcome").style.display = "block";
  localStorage.setItem("greeting", "true")
}

setTimeout(showDiv, 5000); // 5 second delay in MS.

Here is a JS Fiddle for reference 这是一个JS小提琴供参考

Good luck! 祝好运!

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

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