70行代码实现除夕夜倒计时 零基础也能学会~
引言
2022年就要到啦,现在距离过年仅剩20余天,那利用技术制作一个简单的倒计时页面,这个主意不错,开干~
效果图
技术栈
使用到了前端的技术,HTML+CSS+JavaScript,定时去刷新
代码
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
body{
background-color: aliceblue;
}
#msg{
margin: 50px auto;
text-align: center;
font-size: 24px;
font-family: "楷体";
letter-spacing: 10px;
}
span{
color: red;
font-size: 30px;
font-weight: bold;
}
b{
color: blueviolet;
font-size: 34px;
}
#img{
width: 800px;
margin: 50px auto;
}
</style>
<body>
<div id="msg">
</div>
<div id="img">
<img src="C:\Users\王会称\Desktop\文件\image\宝藏\5.jpg" width="800px" alt="">
</div>
</body>
</html>
<script>
//定时执行函数内代码实现倒计时效果
setInterval(function () {
//获取当前日期
let curr_date = new Date();
let current_time = curr_date.getTime();
//设置目标日期
let tgt_date = new Date('2022-01-31 00:00:00');
let target_time = tgt_date.getTime();
//计算出相差的时间,目标日期-当前日期 = 相差日期
let result_time = target_time - current_time;
//计算出天、时、分、秒
let day, hour, minute, second;
if (result_time != '' && result_time > 0) {
day = Math.floor(result_time/1000/60/60/24);
hour = Math.floor(result_time/1000/60/60%60);
minute = Math.floor(result_time/1000/60/60%60);
second = Math.floor(result_time/1000%60);
}
//加0
let str_day = day < 10 ? '0'+day : day;
let str_hour = hour < 10 ? '0'+hour : hour;
let str_minute = minute < 10 ? '0'+minute : minute;
let str_second = second < 10 ? '0'+second : second;
//动态加入div中
document.getElementById("msg").innerHTML = "距离2022年<b>除夕夜</b>仅剩:<span>" + str_day + "</span>天<span>" + str_hour + "</span>时<span>" + str_minute + "</span>分<span>" + str_second + "</span>秒";
}, 1000);
</script>
这里使用了内嵌JavaScript代码
结语
很不错的一个倒计时案例,如果大家喜欢的话,就为我一键三连吧~