[英]Autoclose alert
有什么办法可以自动关闭 javascript alert()
吗?
我有一个警报
alert("Error found");
我想在几秒钟后关闭它。 这是可能的还是我应该去 jQuery 对话
警报无法实现此功能。 但是,您可以使用 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);
}
像这样使用它:
tempAlert("close",1000);
您无法以任何方式关闭警报。
但是您可以使用 div 来显示您的警报 MSG。
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)
基本上你可以模仿一个带有弹出窗口的警告框并在需要时关闭它,调用以下函数:
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”定义为全局变量,然后调用myWindow.close();
一旦你已经调用了 myAlert() 并删除
setTimeout(function(){
myWindow.close(); //close the popup
},timeout||3000) //in 3 secondes (3000 milliseconds)
来自函数 myAlert()
我更新了样式设置,因此它在页面中央显示为启动画面,并将其中的文本居中。
像这样调用它:
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);
}
这是另一种解决方案
window.setTimeout('alert("发现错误");window.close();', 5000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.