簡體   English   中英

如何制作一個在重新加載時重置的 HTML 倒數計時器?

[英]How to make an HTML countdown timer that resets on reload?

我 go 如何僅使用 HTML 和 JS 制作倒計時時鍾? 問題是,有一些功能是必需的: • 它必須在頁面重新加載時重置 • 它必須從頁面加載后的特定小時數開始倒計時(即不是通用時間)

我意識到這些要求很多,但任何提示/技巧/建議都會有所幫助。 提前致謝:]

我試過一些在線計時器,但它們是通用的,不會在頁面重新加載時重置。

我不知道你試過什么。 這是一個。

(雖然,老實說,我可能不應該回答一個寫得不好的問題。)


<div id="countdown"></div>
<script> {
    let remaining = { hours: 1, minutes: 0, seconds: 5 }
    
    displayRemainingTime();

    const countdownInterval = 
    setInterval( () => {

        --remaining.seconds;

        if( remaining.seconds < 0 ) {

            --remaining.minutes;

            if( remaining.minutes < 0 ) {

                --remaining.hours;

                if( remaining.hours < 0 ) {

                    clearInterval( countdownInterval );
                    displayRemainingTime();

                } else {

                    remaining.minutes = 59;
                    remaining.seconds = 59;

                }


            } else {

                remaining.seconds = 59;

            }

        }

        displayRemainingTime();

    }, 1000 );

    function displayTimerFinished() {

        document.getElementById( "countdown" ).textContent = "The timer has finished!";

    }

    function displayRemainingTime() {

        const hoursDigit = remaining.hours < 10 ? "0" : "",
            minutesDigit = remaining.minutes < 10 ? "0" : "",
            secondsDigit = remaining.seconds < 10 ? "0" : "";

        document.getElementById( "countdown" ).textContent =
            `${hoursDigit + remaining.hours}:${minutesDigit + remaining.minutes}:${secondsDigit + remaining.seconds}`;

    }

} </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM