html時(shí)鐘實(shí)現(xiàn)代碼怎么寫

小億
179
2023-07-21 15:39:04
欄目: 編程語言

以下是一個(gè)基本的HTML時(shí)鐘實(shí)現(xiàn)代碼示例:

html

<!DOCTYPE html>

<html>

<head>

  <title>時(shí)鐘</title>

  <style>

    .clock {

      text-align: center;

      font-size: 48px;

      font-weight: bold;

    }

  </style>

  <script>

    function updateClock() {

      var now = new Date();

      var hour = addZeroPrefix(now.getHours());

      var minute = addZeroPrefix(now.getMinutes());

      var second = addZeroPrefix(now.getSeconds());  

      var timeString = hour + ":" + minute + ":" + second;

      document.getElementById("clock").innerHTML = timeString;

      setTimeout(updateClock, 1000); // 每秒鐘更新一次時(shí)鐘

    }    

    function addZeroPrefix(num) {

      return (num < 10 ? "0" : "") + num;

    }

  </script>

</head>

<body onload="updateClock()">

  <div class="clock" id="clock"></div>

</body>

</html>

上述代碼中,我們定義了一個(gè)updateClock()函數(shù)來更新時(shí)鐘,并在頁(yè)面加載完成時(shí)調(diào)用該函數(shù)。updateClock()函數(shù)

獲取當(dāng)前時(shí)間并將其顯示在具有"clock"id的<div>元素中。然后,我們使用setTimeout()函數(shù)每秒鐘調(diào)用一次

updateClock()函數(shù),以便更新時(shí)鐘。

通過上述代碼,您可以在網(wǎng)頁(yè)上實(shí)現(xiàn)一個(gè)簡(jiǎn)單的時(shí)鐘效果。您可以根據(jù)需要自定義CSS樣式以及時(shí)鐘顯示格式。

0