頁面加載後啟動倒計時,顯示剩餘秒數,時間到自動關閉當前窗口。適用於提示頁、中間頁、自動跳轉關閉等場景。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>倒計時關閉窗口</title>
<style>
.countdown-box {
width: 300px;
height: 150px;
margin: 100px auto;
background: #f0f0f0;
border: 1px solid #ddd;
border-radius: 8px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-family: 'Microsoft YaHei', sans-serif;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.countdown-text {
font-size: 18px;
color: #333;
}
.countdown-num {
font-size: 48px;
font-weight: bold;
color: #e74c3c;
font-family: 'Arial', sans-serif;
}
</style>
</head>
<body>
<div class="countdown-box">
<div class="countdown-text">窗口將在</div>
<div class="countdown-num" id="countdown">3</div>
<div class="countdown-text">秒後自動關閉</div>
</div>
<script>
(function() {
var seconds = 3; // 倒計時秒數
var $countdown = document.getElementById('countdown');
function tick() {
seconds--;
$countdown.textContent = seconds;
if (seconds <= 0) {
// 嘗試關閉窗口
// 注意:window.close() 僅能關閉由 window.open() 打開的窗口
// 主窗口直接調用會被瀏覽器攔截或無效
window.close();
} else {
setTimeout(tick, 1000);
}
}
// 頁面加載後啟動
window.onload = function() {
tick();
};
})();
</script>
</body>
</html>
function CountdownCloser(options) {
var opts = Object.assign({
seconds: 5,
selector: '#countdown',
onTick: null, // 每秒回調 function(remaining)
onClose: null, // 關閉前回調
closeMethod: 'auto' // 'auto' | 'openSelf' | 'none'
}, options);
var $el = document.querySelector(opts.selector);
var timerId = null;
var remaining = opts.seconds;
function updateUI() {
if ($el) $el.textContent = remaining;
}
function closeWindow() {
if (opts.onClose) opts.onClose();
if (opts.closeMethod === 'openSelf') {
window.open('', '_self').close();
} else if (opts.closeMethod === 'auto') {
window.close();
}
}
function tick() {
remaining--;
updateUI();
if (opts.onTick) opts.onTick(remaining);
if (remaining <= 0) {
clearTimeout(timerId);
closeWindow();
} else {
timerId = setTimeout(tick, 1000);
}
}
this.start = function() {
updateUI();
timerId = setTimeout(tick, 1000);
};
this.stop = function() {
clearTimeout(timerId);
};
this.reset = function(sec) {
this.stop();
remaining = sec || opts.seconds;
this.start();
};
}
// 使用
var closer = new CountdownCloser({
seconds: 5,
selector: '#countdown',
onTick: function(s) { console.log('剩餘:', s); },
onClose: function() { console.log('關閉了'); }
});
closer.start();
定時關閉窗口看似簡單,但涉及瀏覽器安全策略、定時器選擇、變量作用域等細節。實際項目中建議封裝為可複用組件,並提供友好的用戶交互(如「取消關閉」按鈕)。