本文介绍了利用JavaScript实现网页加载后自动弹出窗口并在指定时间后自动关闭的功能。通过结合window.open、document.open及setTimeout等方法,演示了简单的弹窗特效实现过程,尽管该技术在现代开发中已较少使用,但仍可作为学习参考。
JavaScript自动弹窗与关闭实现
本文介绍了一种使用JavaScript实现自动弹出窗口并在指定时间后自动关闭的方法,供读者参考。
该特效的实现逻辑相对简单:当网页加载时自动弹出一个新窗口,随后该窗口会自动关闭。主要利用了window.open、document.open以及document.close等对象配合完成。需要注意的是,这种技术目前在现代Web开发中已较少使用。
运行效果如下图所示:

具体实现代码如下:
<HTML>
<HEAD>
<TITLE>自动离开的窗口</TITLE>
<SCRIPT>
<!--
var flyingwin
var popupwidth=200
var popupheight=150
var marginright
var windowcenter
var i_top=200
var i_left=-popupwidth-50
var step=40
var timer
var waitingtime=5000
var pause=20
function showWindow() {
flyingwin = window.open("", "flyingwin", "toolbar=no,width="+popupwidth+",height="+popupheight+",top=100,left="+(-popupwidth)+"");
flyingwin.document.open();
flyingwin.document.write("<html><title>自动离开的窗口</title><body><p align=center>请不要关闭,马上就离开:(</body></html>");
flyingwin.document.close();
if (document.all) {
marginright = screen.width+50
}
if (document.layers) {
marginright = screen.width+50
}
windowcenter=Math.floor(marginright/2)-Math.floor(popupwidth/2)
movewindow()
}
function movewindow() {
if (i_left<=windowcenter) {
flyingwin.moveTo(i_left,i_top)
i_left+=step
timer= setTimeout("movewindow()",pause)
}
else {
clearTimeout(timer)
timer= setTimeout("movewindow2()",waitingtime)
}
}
function movewindow2() {
if (i_left<=marginright) {
flyingwin.moveTo(i_left,i_top)
i_left+=step
timer= setTimeout("movewindow2()",pause)
}
else {
clearTimeout(timer)
flyingwin.close()
}
}
// -->
</SCRIPT>
</HEAD>
<BODY onload=showWindow()> </BODY>
</HTML>
希望本文提供的代码示例能对读者的JavaScript程序设计有所帮助。