[JS30] Day02: CSS + JS Clock
CSS
.hand 是指針都有的 class,我們將它以指針尾端為中心旋轉 90 度(transform-origin: 100%)。
.hand {
width: 50%;
height: 6px;
background: black;
position: absolute;
top: 50%;
transform: rotate(90deg);
transform-origin: 100%;
}
JavaScript
利用querySelector抓到時針、分針、秒針。
透過new Date()知道現在時刻,運用三個方法得到時、分、秒,並透過計算得到該時刻的時鐘角度,加上 90 度是因為起點在時鐘數字 9 的地方,加上 90 度才以時鐘數字 0 為起點。
在時針、分針、秒針元素的 style 中,設定新的transform屬性。
透過setInterval每 1000 毫秒(1 秒)呼叫一次 setDate 來更新時間。
const hourHand = document.querySelector(".hour-hand");
const minHand = document.querySelector(".min-hand");
const secondHand = document.querySelector(".second-hand");
function setDate() {
const now = new Date();
const secondDegrees = (now.getSeconds() / 60) * 360 + 90;
const minDegrees = (now.getMinutes() / 60) * 360 + 90;
const hourDegrees = (now.getHours() / 12) * 360 + 90;
secondHand.style.transform = `rotate(${secondDegrees}deg)`;
minHand.style.transform = `rotate(${minDegrees}deg)`;
hourHand.style.transform = `rotate(${hourDegrees}deg)`;
}
setInterval(setDate, 1000);