最近在调整网站前端页面代码时,想实现一个小效果当访问不存在页面时,倒计时几秒后跳转首页。查了下HTML和JavaScript相关文档后简单记录实现过程,希望能帮到有同样需求的同学。

代码部分
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>404页面</title>
</head>
<body>
<p>
抱歉,您访问的页面不存在或已被删除。<br>
系统将在 <span id="countdown">5</span> 秒后自动跳转。
</p>
<script type="text/javascript">
// JavaScript 逻辑部分
(function() {
var timeLeft = 5; // 设置倒计时秒数
var countdownElement = document.getElementById('countdown');
var homeUrl = '/'; // 设置跳转地址
var timer = setInterval(function() {
timeLeft--; // 时间减 1
countdownElement.innerText = timeLeft; // 更新显示的数字
// 如果时间小于等于 0,执行跳转
if (timeLeft <= 0) {
clearInterval(timer); // 清除定时器
window.location.href = homeUrl; // 跳转
}
}, 1000); // 每 1000 毫秒 (1秒) 执行一次
})();
</script>
</body>
</html>JavaScript代码说明
PS:JavaScript代码必须添加在最后
setInterval 函数每秒执行一次。
timeLeft-- 减少剩余时间。
window.location.href = homeUrl 用于执行页面跳转。
注意:代码中的 var homeUrl = '/'; 设置跳转地址


