JavaScript实现自动弹出并关闭窗口的示例
作者:异步漫步时间:2026-10-29 13:19:43浏览:495
本文介绍了利用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程序设计有所帮助。
作者最新文章
D3.js 比例尺与坐标轴的配置详解
2026-11-05 16:54:46
JavaScript怎么遍历对象的Symbol键和不可枚举属性
2026-11-05 13:13:39
封装一个健壮的JS字符串判空工具函数
2026-11-05 12:16:14
JavaScript合并数组的三种常用方法:concat、扩展运算符与push
2026-11-05 11:22:29
JavaScript立即执行函数(IIFE)是什么及基本语法
2026-11-05 10:51:19
