Skip to content
本站總訪問量
本站訪客數 人次

傳統時鐘製作指南

1. 把數字做出來

首先,我們需要在時鐘上顯示數字。這些數字將會以12小時制顯示在時鐘的周圍。

我們使用 JavaScript 來動態生成數字並將其添加到時鐘上:

html
<section class="clock"></section>

<script>
  const clock = document.querySelector(".clock");
  for (let i = 11; i < 23; i++) {
    const idx = i - 11;

    // 360 / 12 = 30
    clock.innerHTML += `
    <div class="num" style="rotate:${idx * 30}deg">
        ${(i % 12) + 1}
    </div>`;
  }
</script>

css 中,為時鐘和數字設置樣式:

css
.clock {
  width: 300px;
  height: 300px;

  border: 5px solid #333;
  border-radius: 50%;
  box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.1);
  font-size: 18px;
  font-weight: bold;

  position: relative;

  display: flex;
  justify-content: center;
  align-items: center;
}

.num {
  width: 95%;
  height: 95%;
  position: absolute;
  text-align: center;
}

2. 在時鐘加增加時分秒針

.clock裡增加3個div

html
<section class="clock">
  <div class="hour"></div>
  <div class="minute"></div>
  <div class="second"></div>
</section>

在 css 中,我們為指針設置樣式:

css
.hour,
.minute,
.second {
  color: #fff;
  background: #222;
  border-radius: 20px;

  position: absolute;
  top: 50%;

  translate: 0 -100%;
  transform-origin: bottom left;

  width: 3px;
}

.hour {
  height: 25%;
}

.minute {
  height: 35%;
}

.second {
  background: red;
  width: 1px;
  height: 45%;
}

3. 讓時鐘動起來

接下來,我們需要讓時鐘的指針根據當前時間進行旋轉。

我們定義了一個 render 函數來更新指針的位置:

html
<script>
  const hour = document.querySelector(".hour");
  const minute = document.querySelector(".minute");
  const second = document.querySelector(".second");

  function render(date) {
    const h = date.getHours();
    const m = date.getMinutes();
    const s = date.getSeconds();
    hour.style.rotate = `${h * 30 + m / 2}deg`; // 360 / 12 = 30
    minute.style.rotate = `${m * 6 + s / 10}deg`; // 360 / 60 = 6
    second.style.rotate = `${s * 6}deg`; // 360 / 60 = 6
  }

  setInterval(() => render(new Date()), 1000); // 每一秒呼叫一次函數
</script>

4. 讓時鐘可以選擇時間

最後,我們需要添加一個時間選擇器,讓用戶可以選擇時間並更新時鐘。

添加一個時間選擇器並設置事件監聽器:

html
<input type="time" id="timer" step="1" />

<script>
  const timer = document.querySelector("#timer");
  timer.addEventListener("change", function () {
    console.log(this.value);

    const time = this.value.split(":");
    const h = time[0];
    const m = time[1];
    const s = time[2];

    render(new Date(0, 0, 0, h, m, s));
  });
</script>

為時間選擇器設置樣式:

css
#timer {
  width: 100%;
  margin: 10px 0 20px;
}

這樣,我們就完成了一個可以顯示數字、動態更新指針並允許用戶選擇時間的傳統時鐘。

DEMO

最後完整體

下載最後完整版本

點我下戴

Contributors

The avatar of contributor named as lucashsu95 lucashsu95

Changelog