有些提示視窗只想短暫存在,時間到就自己關掉。做法是用 setTimeout 讓自己每秒呼叫一次,同時把剩餘秒數顯示出來,倒數歸零時執行 window.close()。
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>定時關閉視窗</title>
<style type="text/css">
.main {
background-color: Silver;
width: 200px;
height: 100px;
margin-left: 40%;
margin-top: 200px;
text-align: center;
}
</style>
<script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var n = 3;
function showTime() {
n--;
$('#divMain').html(n + ' 秒後關閉視窗');
if (n == 0) {
window.close();
} else {
setTimeout('showTime()', 1000);
}
}
</script>
</head>
<body onload="showTime()">
<form id="form1" runat="server">
<div id="divMain" class="main"></div>
</form>
</body>
</html>
把 n 改成 180 就是三分鐘版本,這裡為了方便看結果只設 3。
window.close() 只能關掉由 script 開啟的視窗。如果這個視窗是使用者自己開的,現代瀏覽器會直接忽略這個呼叫,或是在主控台印出警告。所以這段程式要生效,視窗必須是用 window.open() 開出來的,例如:
var w = window.open('notice.html', 'notice', 'width=300,height=200');
若是要關閉使用者自己開的分頁,唯一可行的方式是把它導向其他頁面(location.href = 'about:blank' 或回首頁),而不是真的關掉。
setTimeout 的字串寫法會經歷一次 eval,改成直接傳函式參照比較好:
setTimeout(showTime, 1000);
另外若計時器要能被取消(例如使用者按了「知道了」),應該把 setTimeout 回傳的 id 存起來,取消時用 clearTimeout(id),否則視窗關掉後計時器還在跑,容易出錯。