倒數計時範例
以下範例會顯示 **5 秒倒數**,倒數結束後自動跳轉到指定網址。
## 完整範例
```html
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>倒數跳轉</title>
<style>
body {
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-family: Arial, sans-serif;
background-color: #f4f4f4;
}
.countdown-box {
padding: 30px 50px;
text-align: center;
background-color: white;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
#countdown {
color: #e74c3c;
font-size: 48px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="countdown-box">
<h1>即將跳轉</h1>
<p>
將在 <span id="countdown">5</span> 秒後跳轉到新頁面
</p>
</div>
<script>
let seconds = 5;
const countdownElement = document.getElementById("countdown");
const timer = setInterval(function () {
seconds--;
countdownElement.textContent = seconds;
if (seconds <= 0) {
clearInterval(timer);
// 將網址替換成你要跳轉的網址
window.location.href = "https://www.example.com/";
}
}, 1000);
</script>
</body>
</html>
```
## 程式說明
### 1. HTML
```html
<span id="countdown">5</span>
```
這個元素用來顯示目前剩餘的秒數。
### 2. CSS
CSS 負責設定倒數頁面的外觀,例如:
- 內容置中
- 背景顏色
- 倒數數字大小與顏色
- 卡片陰影與圓角
### 3. JavaScript
```javascript
let seconds = 5;
```
設定倒數起始秒數為 5 秒。
```javascript
const timer = setInterval(function () {
seconds--;
countdownElement.textContent = seconds;
}, 1000);
```
`setInterval()` 每隔 1000 毫秒,也就是 1 秒執行一次,並將秒數減一。
```javascript
if (seconds <= 0) {
clearInterval(timer);
window.location.href = "https://www.example.com/";
}
```
當秒數到達 0 時:
1. 使用 `clearInterval()` 停止計時器
2. 使用 `window.location.href` 跳轉到指定網址
將這一行:
```javascript
window.location.href = "https://www.example.com/";
```
替換成實際要前往的網址即可。
如果不希望使用者按瀏覽器「上一頁」回到倒數頁面,也可以改用:
```javascript
window.location.replace("https://www.example.com/");
```
`replace()` 會取代目前的瀏覽紀錄。
相關學習地圖、教學課程
F2E 網站前端工程