Day2 - CSS+JS Clock 使用setInterval()


Posted by hoyi-23 on 2021-05-11

製作一個時鐘

What's new?


How to do?

quick note

  1. HTML架構
    <div class="clock">
     <div class="clock-face">
         <div class="hand hour-hand"></div>
         <div class="hand min-hand"></div>
         <div class="hand second-hand"></div>
     </div>
    </div>
    
  2. transform-origin 屬性(default是50%)
    瀏覽器在執行2D變形時,以物件元素的中心(50%,50%)做基準點,可藉由transform-origin更改
    transform-origin:x-axis|y-axis|initial|inherit
    (left/center/right/top/bottom/%)
    在製作時鐘時,要更改它的變形基準點!!!

JS

讓秒針轉動 -每一定時間執行一次

setInterval(function,毫秒);

(setInterval()CodePen範例)

const secHand = document.querySelector('second-hand'); //取得秒針
function setDate(){
const now = new Date();
const sec = now.getSeconds(); //抓取現在的秒數
cosnst secDegrees = (sec*6)+90; //圓圈共360度,共60秒,一秒跑360/60=6度;這邊算出每個秒數應該要轉動的度數(加上90是因為我們在css先設定了90度)
secHand.style.transform = `rotate(${secDegrees}deg)`;
}
setInterval(setDate,1000);

依照上面方式,就可以一樣做出分針與時針的轉動!

補充問題 - 轉圈完會閃一下的問題解決

60秒時 - 秒針轉動到最上面為 450 度
0秒時 - 秒針為 90 度
所以在完成一圈後,度數的改變是 450 -> 90 -> 6
從450到90的轉變,transform會視為是逆轉回去(可將transition設1秒,即可更好的觀察)

解決方式:
  1. 使用JS動態更改transition時間
    當秒數為0,角度要轉變成90時,將transition的時間改變為0秒,所以就算是逆轉回去的,我們也看不到xd
    if(secDegrees == 90){
    secHand.style.transition = all 0s
    }else{secHand.style.transition = all 0.5s
    };
    

VVV 我的所有筆記與demo在這裡 VVV
https://github.com/hoyi-23/JavaScript30










Related Posts

目錄-資料傳輸物件資訊

目錄-資料傳輸物件資訊

ElementPlus的自定義主題

ElementPlus的自定義主題

Win10 20H2更新 不相容Virtual Box

Win10 20H2更新 不相容Virtual Box


Comments