JavaScript实现网页倒计时并跳转页面

背景

之前想自己从头搭建一个个人博客,后来各种原因直接用了hexo并托管在coding上,效果也不错。于是打算在个人服务器上直接建一个倒计时跳转页面,转到hexo, 也不浪费自己买的域名,哈哈哈。本来想直接跳转,感觉还是有一个倒计时提醒比较好一点。

思路

  • 首先先写一个html5的简单的文字页面就好,留出一个div放倒计时的数字就好了。

  • 然后JavaScript中可以用setInterval来实现按周期调用函数功能,也就是倒计时,每过一秒,数字减1。

    setInterval()方法是按照指定的周期(毫秒)来调用函数或计算表达式。

    1
    2
    // 每三秒(3000 毫秒)弹出 "Hello" :
    setInterval(function(){ alert("Hello"); }, 3000);

    http://www.runoob.com/jsref/met-win-setinterval.html

  • 页面跳转就比较简单了location.href=就可以实现跳转了。

  • 最后整个函数需要在页面加载完成之后进行,也就是放在window.onload里。

    window.onload事件会在页面或者图像加载完成后立刻发生,通常用于<body>元素。

    1
    2
    3
    4
    // html中
    <body onload="SomeJavaScriptCode">
    // js中
    window.onload=function(){SomeJavaScriptCode};

    http://www.runoob.com/jsref/event-onload.html

实现

根据上面的思路,实现就比较简单了,在页面部分显示倒计时数字的div设置了id="time",在onload事件中,每隔1000毫秒调用一次函数使倒计时数字减1,当倒计时结束时跳转页面。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>图兰登</title>
</head>
<body>
<div>
<div style="text-align: center;">
<h1>你好,这里是图兰登。</h1>
<h3>欢迎进入我的个人博客!</h3>
<div style="text-align: center">
<div style="display: inline-block">倒计时:</div>
<div id="time" style="display: inline-block"></div>
</div>
</div>
</div>
</body>
<script>
window.onload = function () {
let oDiv = document.getElementById("time");
let count = 5;
oDiv.innerHTML = count;
let timer = null;
timer = setInterval(function () {
if (count > 0) {
count = count - 1;
oDiv.innerHTML = count;
}
else {
location.href='http://keejo.coding.me'
}
}, 1000);
}
</script>
</html>

最终效果可以见链接:https://www.torandom.com

transfer