[70 lines of JavaScript code to realize the New Year's Eve countdown with zero basis can also be learned~

70 lines of code to realize the New Year's Eve countdown with zero basis can also be learned~

introduction

2022 is coming, and now there are only 20 days left before the Chinese New Year, so use technology to make a simple countdown page, this is a good idea, let's do it~

renderings

insert image description here

technology stack

Using the front-end technology, HTML+CSS+JavaScript, to refresh regularly

code

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>

Inline JavaScript code is used here

Epilogue

A very good countdown case, if you like it, just click three times for me~

Guess you like

Origin blog.csdn.net/weixin_45526437/article/details/122301877