第5章项目 毕业倒计时

作者: liufeisheng

创建时间: 2024-03-26 00:44:09


   张华同学最近在看人才招聘信息,发现人才竞争非常激烈,感慨一定要珍惜大学时光,多学点儿知识,又感叹时间过得真快,这个学期过去一半了,距离毕业只有不到两年的时间了。他向李老师请教,想利用所学的知识做一个毕业倒计时页面,如图所示。李老师告诉他,这需要用到面向对象的知识。JavaScript是一种基于对象的程序设计语言,基于对象编程是JavaScript的基本编程思想。

image.png

html文件

image.png

效果图

image.png

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title> 毕业倒计时</title>
        <script src="js5.js"></script>
        <style >@import url(js5.css);</style>
    </head>
    <body>
        <p>距离2026年毕业还有</p>
        <ul>
            <li>
                <span id="day"></span><br>
                <span class="title">天</span>
            </li>
            <li>
                <span id="hour"></span><br>
                <span class="title">时</span>
            </li>
            <li>
                <span id="min"></span><br>
                <span class="title">分</span>
            </li>
            <li>
                <span id="sec"></span><br>
                <span class="title">秒</span>
            </li>
        </ul>
    </body>
</html>

css

image.png

image.png

body{
    background-color: #fef4d2;
}
p{
    text-align: center;
    font-size: 30px;
}
ul{
    width: 400px;
    margin: 0 auto;
    list-style: none;
    color:white;
}
li{
    float: left;
    width: 80px;
    height: 80px;
    background-color: #6312E7;
    margin-left: 10px;
    font-weight: bold;
    font-size: 30px;
    text-align: center;
}
.title{
    font-size: 20px;
}

js

image.png

ps:在这需要注意, js代码得放在 body内的ul标签之后,才能修改前面的标签内容生效

image.png

function calcute(){
    var  now = new Date();
    var sports = new Date("2026,6,30");
    var leftSeconds = (sports.getTime()-now.getTime())/1000;
    var daysLeft = Math.floor(leftSeconds/3600/24);
    var hoursLeft = Math.floor(leftSeconds/60/60%24);
    var minutesLeft = Math.floor(leftSeconds/60%60);
    var secondsLeft = Math.floor(leftSeconds%60);
    document.querySelector("#day").innerHTML = daysLeft;    
    document.querySelector("#hour").innerHTML = hoursLeft;
    document.querySelector("#min").innerHTML = minutesLeft;
    document.querySelector("#sec").innerHTML = secondsLeft;
    setTimeout(calcute,1000);  // 每秒刷新一次
}
calcute();