下篇我們要接續上篇的時鐘來講解
主要圍繞在JS的部分
let hour = document.querySelector(".hour");
let minute = document.querySelector(".minute");
let second = document.querySelector(".second");
let time = document.querySelector(".time");
let date = document.querySelector(".date");
let toggle = document.querySelector(".toggle");
存放月和日的陣列
let days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
let months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", "Sep", "Oct","Nov","Dec"];
背景切換
toggle.addEventListener('click', (e) => {
//root element
let html = document.querySelector('html')
if (html.classList.contains('dark')) {
html.classList.remove('dark')
e.target.innerHTML = 'Dark mode'
} else {
html.classList.add('dark')
e.target.innerHTML = 'Light mode'
}
})
時間設定
function setTime() {
const time = new Date();
const month = time.getMonth();
const day = time.getDay();
const date = time.getDate();
const hours = time.getHours();
const hoursForClock = hours >= 13 ? hours % 12 : hours;
const minutes = time.getMinutes();
const seconds = time.getSeconds();
const ampm = hours >= 12 ? "PM" : "AM";
// 時
hourEl.style.transform = `translate(-50%, -100%) rotate(${scale(
hoursForClock,
0,
12,
0,
360
)}deg)`;
// 分
minuteEl.style.transform = `translate(-50%, -100%) rotate(${scale(
minutes,
0,
60,
0,
360
)}deg)`;
// 秒
secondEl.style.transform = `translate(-50%, -100%) rotate(${scale(
seconds,
0,
60,
0,
360
)}deg)`;
timeEl.innerHTML = `${hoursForClock}:${
minutes < 10 ? `0${minutes}` : minutes
} ${ampm}`;
dateEl.innerHTML = `${days[day]}, ${months[month]} <span class="circle">${date}</span>`;
}
let scale = (number, inMin, inMax, outMin, outMax) {
return ((number - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
}
setTime();
setInterval(setTime, 1000);
以上scale變數的函式是參考stackoverflow上提供的,將一個值對應到另一個值的函式
附上codepen連結 https://codepen.io/hangineer/pen/yLjorLj