Автозаполнение оповещения
Есть ли способ закрыть JavaScript alert()
автоматически?
У меня есть предупреждение
alert("Error found");
Я хочу закрыть его через несколько секунд. Это возможно, или я пойду на диалог JQuery
5 ответов
Эта функция невозможна с предупреждением. Тем не менее, вы можете использовать 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)
}
кстати, если вы хотите закрыть оповещение при вызове, просто используйте определение переменной "myWindow" ранее (из функции myAlert()) как глобальную переменную, а затем вызовите 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);