Javascript 小型專案練習4-Clock(JS30-2)

這個小專案是來自https://javascript30.com/的教學,點擊進去輸入email後就可以進入課程~!此為第二篇學習紀錄!一樣先附上程式碼

HTML

<body>
  <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>
  <script src="main.js"></script>
</body> 

CSS

 html {
      background: #018DED ;
      background-size: cover;
      font-family: 'helvetica neue';
      text-align: center;
      font-size: 10px;
    }

    body {
      margin: 0;
      font-size: 2rem;
      display: flex;
      flex: 1;
      min-height: 100vh;
      align-items: center;
    }

    .clock {
      width: 30rem;
      height: 30rem;
      border: 20px solid white;
      border-radius: 50%;
      margin: 50px auto;
      position: relative;
      padding: 2rem;
      box-shadow:
        0 0 0 4px rgba(0,0,0,0.1),
        inset 0 0 0 3px #EFEFEF,
        inset 0 0 10px black,
        0 0 10px rgba(0,0,0,0.2);
    }

    .clock-face {
      position: relative;
      width: 100%;
      height: 100%;
      transform: translateY(-3px); /* account for the height of the clock hands */
    }

    .hand {
      width: 50%;
      height: 6px;
      background: black;
      position: absolute;
      top: 50%;
      transform-origin: 100%;
      transition: all 0.05s;
      transform: rotate(90deg);
    } 

Javascript

 (function setDate() {
  const secondHand = document.querySelector('.second-hand')
  const minHand = document.querySelector('.min-hand')
  const hourHand = document.querySelector('.hour-hand')
  //建立Date物件取得現在時間
  const now = new Date()
  //取得現在秒數與對應的角度,度數+90是因為原先時針是指向9點鐘方向
  const second = now.getSeconds();
  const secondDegrees = ((second / 60) * 360) + 90
  //取得現在分鐘與對應的角度,度數+90是因為原先時針是指向9點鐘方向
  const minute = now.getMinutes();
  const minuteDegrees = ((minute / 60) * 360) + 90
  //取得現在小時與對應的角度,度數+90是因為原先時針是指向9點鐘方向
  const hour = now.getHours();
  const hourDegrees = ((hour / 60) * 360) + 90
  //根據度數旋轉三根指針
  secondHand.style.transform = `rotate(${secondDegrees}deg)`
  minHand.style.transform = `rotate(${minuteDegrees}deg)`
  hourHand.style.transform = `rotate(${hourDegrees}deg)`
  //每一千毫秒執行一次程式
  setInterval(setDate, 1000);
})(); 

學習重點

  • 利用position:absolute讓三個元素完美重疊
  • 利用transform:rotate(xdeg)讓元素旋轉,但預設為以中心旋轉,若希望元素以最右端為軸心旋轉則需要 transform-origin:100%(right也行)
  • 加入transition: all 0.05s會讓transform的過程更順暢,也可以設定 transition timing function 改變動畫的類型。關於transition的用法可以參考底部的參考文章。
  • 利用setInterval()可以在指定間隔中重複執行函數,用法類似setTimeOut
  • 照原先的教案會有些小瑕疵,所以我將函數改為IIFE 目的是一進入畫面就顯示正確的時間而不是預設的畫面(指針全部指向12點方向) 。 後來發現在本機端看問題是解決了,不過上傳gitpages問題又出現 待解決。

最終成品

https://windate3411.github.io/clock-JS30-2-/

參考文章

[CSS][Transition] 轉場效果

發表留言