js实现倒计时页面跳转
实现倒计时页面跳转的方法
使用JavaScript实现倒计时并在倒计时结束后自动跳转页面,可以通过以下方法完成:
设置倒计时变量和显示
let countdown = 5; // 倒计时5秒
const countdownElement = document.getElementById('countdown'); // 显示倒计时的元素
function updateCountdown() {
countdownElement.textContent = countdown;
countdown--;
if (countdown < 0) {
clearInterval(timer);
window.location.href = 'https://example.com'; // 跳转目标URL
}
}
const timer = setInterval(updateCountdown, 1000); // 每秒更新一次
HTML部分

<div>
页面将在 <span id="countdown">5</span> 秒后自动跳转...
</div>
使用setTimeout实现
另一种更简单的方法是使用setTimeout:
setTimeout(() => {
window.location.href = 'https://example.com';
}, 5000); // 5000毫秒=5秒后跳转
添加进度条效果
如果需要更直观的显示,可以添加进度条:

const progressBar = document.getElementById('progress');
let width = 100;
const interval = 50; // 更新频率(毫秒)
const duration = 5000; // 总时长(毫秒)
const increment = (interval / duration) * 100;
const progressTimer = setInterval(() => {
width -= increment;
progressBar.style.width = width + '%';
if (width <= 0) {
clearInterval(progressTimer);
window.location.href = 'https://example.com';
}
}, interval);
对应的HTML
<div class="progress-container">
<div id="progress" class="progress-bar"></div>
</div>
CSS样式
.progress-container {
width: 100%;
height: 5px;
background: #eee;
}
.progress-bar {
height: 100%;
background: #4CAF50;
width: 100%;
transition: width 0.05s linear;
}
注意事项
- 确保跳转URL正确无误
- 考虑添加取消跳转的按钮
- 在移动设备上测试效果
- 如果页面内容重要,建议提供明显的手动跳转链接
完整示例代码
<!DOCTYPE html>
<html>
<head>
<style>
.progress-container {
width: 100%;
height: 5px;
background: #eee;
margin: 10px 0;
}
.progress-bar {
height: 100%;
background: #4CAF50;
width: 100%;
}
#cancel-btn {
margin-top: 10px;
padding: 5px 10px;
cursor: pointer;
}
</style>
</head>
<body>
<div>
页面将在 <span id="countdown">5</span> 秒后自动跳转...
</div>
<div class="progress-container">
<div id="progress" class="progress-bar"></div>
</div>
<button id="cancel-btn">取消跳转</button>
<script>
let countdown = 5;
const countdownElement = document.getElementById('countdown');
const progressBar = document.getElementById('progress');
const cancelBtn = document.getElementById('cancel-btn');
let width = 100;
const interval = 50;
const duration = 5000;
const increment = (interval / duration) * 100;
let progressTimer = setInterval(() => {
width -= increment;
progressBar.style.width = width + '%';
if (width <= 0) {
clearInterval(progressTimer);
window.location.href = 'https://example.com';
}
}, interval);
let countdownTimer = setInterval(() => {
countdown--;
countdownElement.textContent = countdown;
if (countdown <= 0) {
clearInterval(countdownTimer);
}
}, 1000);
cancelBtn.addEventListener('click', () => {
clearInterval(progressTimer);
clearInterval(countdownTimer);
countdownElement.textContent = '已取消';
progressBar.style.width = '100%';
progressBar.style.backgroundColor = '#ccc';
});
</script>
</body>
</html>






