自动关闭警告

14

有没有办法自动关闭 JavaScript 的 alert() 弹窗?

我有一个弹窗。

alert("Error found");

我想在几秒钟后关闭它。这可能吗,还是我应该使用jQuery对话框?


1
我不认为这是可能的;在6年的编程经验中从未见过。 - Joe Simmons
@sreeekesh 你不能关闭一个警告框,只能隐藏它。 - HybrisHelp
@ankit337:怎么隐藏它? - Joe Simmons
1
https://dev59.com/NmUp5IYBdhLWcg3wLVKn - Nikolay Talanov
谢谢大家。我想我会选择jQuery对话框 :) - Okky
显示剩余2条评论
5个回答

17

jsFiddle演示

使用alert无法实现此功能。但是,您可以使用

元素。

function tempAlert(msg,duration)
{
 var el = document.createElement("div");
 el.setAttribute("style","position:absolute;top:40%;left:20%;background-color:white;");
 el.innerHTML = msg;
 setTimeout(function(){
  el.parentNode.removeChild(el);
 },duration);
 document.body.appendChild(el);
}

像这样使用:

tempAlert("close",1000);

3

你不能随意关闭警报。但是,你可以使用div来展示你的警报消息。

  function Mymsg(msg,duration)
{
 var alt = document.createElement("div");
     alt.setAttribute("style","position:absolute;top:50%;left:50%;background-color:white;");
     alt.innerHTML = msg;
     setTimeout(function(){
      alt.parentNode.removeChild(alt);
     },duration);
     document.body.appendChild(alt);
}

你可以这样使用:

Mymsg('close',2000)

3

jsFiddle演示

基本上,您可以通过弹出窗口模拟警报框,并在需要时关闭它,调用以下函数:

function myAlert(msg,title,width,height,timeout) {
    var myWindow = window.open("", "",`width=${width},height=${height},left=${(window.outerWidth/2-width/2)},top=0`); //open a new popup at the top height and middle width of the current window
    myWindow.document.write(`<center id="msg">`+msg+`</center>`); //write the message you want to display
    myWindow.document.title = title; //write the title of the alert box
    setTimeout(function(){
        myWindow.close(); //close the popup
    },timeout||3000) //in 3 secondes (3000 milliseconds)
}

顺便提一下,如果你想在调用时关闭警告框,只需要在 myAlert() 函数之外先定义变量 "myWindow" 作为全局变量,然后在调用 myAlert() 后调用 myWindow.close(); 就可以了,记得移除


setTimeout(function(){
    myWindow.close(); //close the popup
},timeout||3000) //in 3 secondes (3000 milliseconds)

由函数 myAlert() 产生

2

我更新了样式设置,使其在您的页面中央显示为闪屏,并将文本居中对齐。

按以下方式调用:

alertTimeout("System Message<br>This is a test message<br>This alert will auto-close",5000)

这个函数:

function alertTimeout(mymsg,mymsecs)
{
 var myelement = document.createElement("div");
myelement.setAttribute("style","background-color: grey;color:black; width: 450px;height: 200px;position: absolute;top:0;bottom:0;left:0;right:0;margin:auto;border: 4px solid black;font-family:arial;font-size:25px;font-weight:bold;display: flex; align-items: center; justify-content: center; text-align: center;");
 myelement.innerHTML = mymsg;
 setTimeout(function(){
  myelement.parentNode.removeChild(myelement);
 },mymsecs);
 document.body.appendChild(myelement);
}

-2

这是另一种解决方案

window.setTimeout('alert("发现错误");window.close();', 5000);


3
不是关闭警告,而是整个页面。 - Michal Miky Jankovský

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接