iT邦幫忙

2022 iThome 鐵人賽

DAY 17
0
自我挑戰組

在30天利用HTML & CSS & JavaScript完成Side Project實作系列 第 17

Day 17 Side Project : Theme Clock 動態時鐘(下)

  • 分享至 

  • xImage
  •  


下篇我們要接續上篇的時鐘來講解
主要圍繞在JS的部分

  • 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


上一篇
Day 16 Side Project : Theme Clock 動態時鐘(上)
下一篇
Day 18 Side Project : Drag N Drop 拖與拉
系列文
在30天利用HTML & CSS & JavaScript完成Side Project實作30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言