简体   繁体   English

如何延迟使用 Javascript 制作的警报框?

[英]How do I put a delay on an Alert Box made with Javascript?

I have an alert box that pops up if someone enters a website using Internet Explorer.如果有人使用 Internet Explorer 进入网站,我会弹出一个警告框。 The problem I am having is that the alert shows up instantly, so sometimes the previous website is still visible when the alert shows up.我遇到的问题是警报会立即显示,因此有时当警报出现时,以前的网站仍然可见。 I need to put on a delay, so that the website can load up before the alert shows up - or make it only show once everything is loaded.我需要延迟,以便网站可以在警报出现之前加载 - 或者仅在所有内容加载后才显示。 I use Wordpress.我使用 WordPress。

I have tried numerous pieces of code that I found online, but unfortunately none of them has worked for me, mainly because I dont know how to "include it" with the code I already have (which I got from a different Stack Overflow thread)我已经尝试了很多我在网上找到的代码,但不幸的是,它们都没有对我有用,主要是因为我不知道如何将它“包含”到我已经拥有的代码中(我从不同的 Stack Overflow 线程中获得)

function isIE() {
  ua = navigator.userAgent;

  /* MSIE used to detect old browsers and Trident used to newer ones*/
  var is_ie = ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1;

  return is_ie; 
}
/* Create an alert to show if the browser is IE or not */
if (isIE()){
    alert('MY ALERT MESSAGE');
}

I want the alert to show up after the page has been loaded, either in form of a delay or by using onload.我希望在加载页面后以延迟或使用 onload 的形式显示警报。 Javascript "only" is prefered since I work with a webpage builder that does not like jQuery. “仅”Javascript 是首选,因为我使用不喜欢 jQuery 的网页构建器。

Wrap you statement in setTimeout.将您的语句包装在 setTimeout 中。 Time is in miliSeconds时间以毫秒为单位

if (isIE()){
    setTimeout(function () {
        alert('MY ALERT MESSAGE');
    }, 1000);
}

I recommend adding the script tag at the bottom of the page, or use the onload of the body element.我推荐在页面底部添加script标签,或者使用body元素的onload

In both cases, the alert will come after the html has reached the user.在这两种情况下,警报都会在 html 到达用户之后出现。


Another more elegant way could be to make a small modal yourself, ie create your own "alert".另一种更优雅的方法可能是自己制作一个小模态,即创建自己的“警报”。 By default, you hide it, and show it when the user has IE:默认情况下,您隐藏它,并在用户拥有 IE 时显示它:

// CSS
#browserWarning{
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%);
    background: #FFF;
    padding: 25px;
}

// Javascript
if (isIE()){
    document.getElementById("browserWarning").style.display = 'block';
}

You can now crate something that looks a bit better, allows for a bit more explanation (I'm assuming "IE not supported because" messages here), and because it's non-blocking, the rest of your page keeps on loading.您现在可以创建看起来更好的东西,允许更多的解释(我假设“IE 不支持,因为”这里的消息),并且因为它是非阻塞的,所以页面的其余部分会继续加载。

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

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