javascript 显示后如何自动隐藏警报框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15466802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I auto hide alert box after it showing it?
提问by maherelghali
All I want to do is, how can I auto hide alert box within specific seconds after showing it?
我想要做的就是,如何在显示后的特定秒内自动隐藏警报框?
All I know is,
我只知道,
setTimeout(function() {
alert('close');
}, 5000);
// This will appear alert after 5 seconds
No need for this I want to disappear alert after showing it within seconds.
不需要这个我想在几秒钟内显示后消失警报。
Needed scenario :
需要的场景:
Show alert
Hide/terminate alert within 2 seconds
显示警报
在 2 秒内隐藏/终止警报
回答by Travis J
tldr; jsFiddle Demo
tldr; jsFiddle 演示
This functionality is not possible with an alert. However, you could use a div
警报无法实现此功能。但是,您可以使用 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);
}
Use this like this:
像这样使用它:
tempAlert("close",5000);
回答by Doorknob
You can't close an alert box with Javascript.
您无法使用 Javascript 关闭警报框。
You could, however, use a window instead:
但是,您可以改用窗口:
var w = window.open('','','width=100,height=100')
w.document.write('Message')
w.focus()
setTimeout(function() {w.close();}, 5000)
回答by Alex Shesterov
impossible with javascript. Just as another alternative to suggestions from other answers: consider using jGrowl: http://archive.plugins.jquery.com/project/jGrowl
用 javascript 不可能。正如其他答案的建议的另一种替代方法:考虑使用 jGrowl:http: //archive.plugins.jquery.com/project/jGrowl
回答by Jason Stackhouse
You can also try Notification API. Here's an example:
您也可以尝试通知 API。下面是一个例子:
function message(msg){
if (window.webkitNotifications) {
if (window.webkitNotifications.checkPermission() == 0) {
notification = window.webkitNotifications.createNotification(
'picture.png', 'Title', msg);
notification.onshow = function() { // when message shows up
setTimeout(function() {
notification.close();
}, 1000); // close message after one second...
};
notification.show();
} else {
window.webkitNotifications.requestPermission(); // ask for permissions
}
}
else {
alert(msg);// fallback for people who does not have notification API; show alert box instead
}
}
To use this, simply write:
要使用它,只需编写:
message("hello");
Instead of:
代替:
alert("hello");
Note:Keep in mind that it's only currently supported in Chrome, Safari, Firefox and some mobile web browsers (jan. 2014)
注意:请记住,它目前仅在 Chrome、Safari、Firefox 和一些移动网络浏览器中受支持(2014 年 1 月)
Find supported browsers here.