首页 > 解决方案 > 在 HTML 中添加了倒数计时器,显示问题

问题描述

请就一个问题提出建议。

我使用 HTML、CSS 和 JS 创建了一个带有倒数计时器的登录页面。倒数计时器确实可以工作,但会在一段时间后停止工作,并显示设置为 00:00:00:00 的默认值。

请指教,我似乎没有纠正编码中的任何错误。

编写的 HTML 代码

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width-device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Countdown Timer</title>
        
        <link rel="stylesheet" href="main.css" />
    </head>
    <body>
        <section class = "sec">
            <h1 class = "coming">COMING SOON</h1>
        </section> 
        <header>
            <div class="heading">
                <h1>University <span>of </span>Saskatchewan</h1>
                <h2>Arts & Science College</h2>
                <div class="countdown">00 : 00 : 00 : 00</div>
                <div class="def">Days : Hours : Mins : Secs</div>
                <style>
                    .def{
                        color: white;
                        justify-content: center;
                        text-align: center;
                        margin-top: 10pt;
                 
                    }
                </style>
            </div>
        </header>
        
        <script src="main.js"></script>
    </body>
</html>

编写的JS代码

let newDate = new Date("Dec 8, 2020 00:00:00").getTime();
let t = setInterval(sec, 1000);

function sec () {

    let todayDate = new Date().getTime();

    let diff = newDate - todayDate;

    if (diff  > 0){
        let d = Math.floor(diff / (1000 * 60 * 60 * 24));
        if (d < 10) { d = "0" + d;}
        
        let h = Math.floor(((diff % (1000 * 60 * 60 * 24)) / (1000*60*60)));
        if (h < 10 ) {h = "0" + hours;}

        let m = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
        if(m <10) {m = "0" + m;}

        let s = Math.floor((diff % (1000 * 60)) / 1000);
        if (s < 10 ){s = "0" + s;}

        let newTime = `${d} : ${h} : ${m} : ${s}`

        document.getElementById("countdown").innerHTML = newTime;


    
    }
}

标签: javascripthtmlcsssasscountdowntimer

解决方案


推荐阅读