Please enable Javascript to view the contents

【JS30系列】Day 02:CSS + JS Clock

 ·  ☕ 2 分鐘 · 👀... 閱讀
CSS + JS Clock
Javascript 30 Day02: CSS + JS Clock

Wes Bos 的原始專案:JS30 Day02

專案目標:

製作一個時、分、秒針能實時運轉的小時鐘。


我的解法:

實作成果

1
2
3
4
5
6
7
8
9
.hand {
  width: 0;
  height: 0;
  position: absolute;
  top: 50%;
  border-style: solid;
  border-width: 3px 15rem 3px 0;
  transform-origin: 100%;
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const hourHand = document.querySelector('.hour-hand');
const minHand = document.querySelector('.min-hand');
const secondHand = document.querySelector('.second-hand');
const hourInfo = document.querySelector('.hour-info');
const minInfo = document.querySelector('.min-info');
const hourDeg = 360 / 12;
const minDeg = 360 / 60;
const secondDeg = 360 / 60;

function setTime(){
  const NOW = new Date();
  const nowHour = NOW.getHours();
  const nowMin = NOW.getMinutes();
  const nowSecond = NOW.getSeconds();
  const hourTranDeg = (nowHour % 12)*hourDeg + nowMin/2;
  const minTranDeg = nowMin*minDeg;
  const secondTranDeg = nowSecond*secondDeg;
  hourHand.style.transform = `rotate(${hourTranDeg+90}deg)`;
  minHand.style.transform = `rotate(${minTranDeg+90}deg)`;
  secondHand.style.transform = `rotate(${secondTranDeg+90}deg)`;
  hourInfo.innerText = nowHour;
  minInfo.innerText = nowMin;
  hourInfo.style.transform = `rotate(${360-(hourTranDeg+90)}deg)`;
  minInfo.style.transform = `rotate(${360-(minTranDeg+90)}deg)`;
}

setInterval(setTime, 1000);
setTime();


觀念一:new Date() 抓取當前時間

建立一個變數來存取當前時間資訊。
其中包含年、月、日、時、分、秒資訊。

1
2
const NOW = new Date();
// Wed Oct 20 2021 19:36:34 GMT+0800 (台北標準時間) {}


觀念二:getHours()、getMinutes()、getSeconds()獲取當前時、分、秒資訊

使用 getHours()getMinutes()getSeconds() 方法來從剛剛建立的 NOW 變數中分別提取時分秒資訊。

1
2
3
const nowHour = NOW.getHours();
const nowMin = NOW.getMinutes();
const nowSecond = NOW.getSeconds();


觀念三:transform-origin 設定旋轉軸心

transform-origin 可以用來設定旋轉軸心。
由於指針初始設定是由時鐘正中心指向 9 點鐘方向,所以設定的軸心是指針的最右側,故在此範例中 transform-origin 設定為 100%
並搭配 transform: rotate(90deg); ,以 0 點為起點開始旋轉,所以要先旋轉 90 度。


延伸閱讀:



觀念四:setInterval 設定間隔時間,重複執行程式

setTimeout() 方法用於在指定的毫秒數後呼叫函式或計算表示式。

setInterval() 方法則是在每隔指定的毫秒數迴圈呼叫函式或表示式,直到clearInterval把它清除。

也就是說 setTimeout() 只執行一次,setInterval() 可以執行多次。

因為在此範例中是每秒都要重新獲取一次時間資訊,所以使用 setInterval()



分享

Sylvia-H
作者
Sylvia-H
Web Developer / F2E 前端筆記

comments powered by Disqus