Javascript close alert box

2019-01-02 18:23发布

I want to be able to close an alert box automatically using javascript after a certain amount of time or on a specific event (i.e. onkeypress). From my research, it doesn't look like that's possible with the built-in alert() function. Is there a way to override it and have control over the dialog box that it opens?

Also, I don't want an override that shows a hidden div as the alert. I need an actual dialog box.

10条回答
冷夜・残月
2楼-- · 2019-01-02 18:57

Appears you can somewhat accomplish something similar with the Notification API. You can't control how long it is visible (probably an OS preference of some kind--unless you specify requireInteraction true), and it requires the user to click "allow notifications" (unfortunately), but here it is:

If you want it to close after 1s:

var notification = new Notification("Hi there!", {body: "some text"});
setTimeout(function() {notification.close()}, 1000);

If you wanted to show it longer than the "default" you could bind to the onclose callback and show another repeat notification I suppose, to replace it.

Ref: inspired by this answer, though that answer doesn't work in modern Chrome anymore, but the Notification API does.

查看更多
只若初见
3楼-- · 2019-01-02 18:58

The only real alternative here is to use some sort of custom widget with a modal option. Have a look at jQuery UI for an example of a dialog with these features. Similar things exist in just about every JS framework you can mention.

查看更多
流年柔荑漫光年
4楼-- · 2019-01-02 18:58

You can use label and set its fade in and out time for e.g Hide it initially and show on click. $('#div_Message').fadeIn(500).delay(1000).fadeOut(1500);

查看更多
荒废的爱情
5楼-- · 2019-01-02 19:03
window.setTimeout('alert("Message goes here");window.close();', 5000);
查看更多
与君花间醉酒
6楼-- · 2019-01-02 19:06

I guess you could open a popup window and call that a dialog box. I'm unsure of the details, but I'm pretty sure you can close a window programmatically that you opened from javascript. Would this suffice?

查看更多
伤终究还是伤i
7楼-- · 2019-01-02 19:07

As mentioned previously you really can't do this. You can do a modal dialog inside the window using a UI framework, or you can have a popup window, with a script that auto-closes after a timeout... each has a negative aspect. The modal window inside the browser won't create any notification if the window is minimized, and a programmatic (timer based) popup is likely to be blocked by modern browsers, and popup blockers.

查看更多
登录 后发表回答