显示后如何自动隐藏警告框?

mah*_*ali 24 javascript

我想要做的就是,如何在显示后的特定秒内自动隐藏警报框?

我所知道的是,

setTimeout(function() { 
      alert('close'); 
}, 5000);

// This will appear alert after 5 seconds
Run Code Online (Sandbox Code Playgroud)

不需要这个我想在几秒钟内显示它后消失警报.

需要的场景:

  1. 显示提醒

  2. 在2秒内隐藏/终止警报

Tra*_*s J 24

tldr; jsFiddle演示

警报无法实现此功能.但是,你可以使用div

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);
}
Run Code Online (Sandbox Code Playgroud)

像这样用:

tempAlert("close",5000);
Run Code Online (Sandbox Code Playgroud)