iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 2
0
自我挑戰組

JavaScript 30天系列 第 2

JS30 - day02: JS + CSS Clock

來到了day2 利用上班兩小時給他學下去
這次覺得較困難的其實是數學呀QQ

https://ithelp.ithome.com.tw/upload/images/20181010/20111164e4v4a2M2PQ.png

使用者操作需求

雙眼看著它,取得目前時間資訊

技術重點

  • 更改角度 transform: rotate(90deg)

  • 更改物件中心點位置,預設為中心 transform-oragin:50%
    在這更改為 100%(right)

  • 更改動畫曲線 transition-timing-function: cubic-bezier()

  • 定時器:setInterval(function, mins)

  • 取得當前時間函式,要搭配new使用,new.Date();

    • getSeconds() 取得秒數
    • getMinutes() 取得分數
    • getHours() 取得時數

流程步驟:

  1. transform預設好秒分時針的角度
  2. 使用定時器setInterval 每秒取得當前時間
  3. 利用當前時間來計算出角度

// css部分

    .hand {
      width: 50%;
      height: 6px;
      background: black;
      position: absolute;
      top: 50%;

      transform-origin: 100%; /* 改變物件中心點位置 */
      transform: rotate(90deg); /* 預設角度 */
      transition: all 0.05s;
      transition-timing-function: cubic-bezier(0, 2.69, 0.58, 1); /* 動畫曲線 */
    }

//JS部分

  <script>
    const secondHand = document.querySelector('.second-hand');
    const minHand = document.querySelector('.min-hand');
    const hourHand = document.querySelector('.hour-hand');

    function setDate(){
      // 取得時間
      const now = new Date();
      
      // 取得秒數
      const seconds = now.getSeconds();
      const secondsDegrees = ((seconds / 60) * 360) + 90;
      secondHand.style.transform = `rotate(${secondsDegrees}deg)`;
      
      // 取得分數
      const mins = now.getMinutes();
      const minsDegrees = ((mins / 60) * 360) + 90;
      minHand.style.transform = `rotate(${minsDegrees}deg)`;
      
      // 取得時數
      const hour = now.getHours();
      const hourDegrees = ((hour / 12) * 360) + 90;
      hourHand.style.transform = `rotate(${hourDegrees}deg)`;
    }

    // 設定定時器
    setInterval(setDate, 1000);

  </script>

上一篇
JS30 - day01: JS Drum Kit
下一篇
JS30 - day03: CSS Variable
系列文
JavaScript 30天11
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
smit
iT邦新手 5 級 ‧ 2018-10-15 10:33:11

不好意思,我跟著實作了一下,我的秒針在59>60秒時候,會有個很不自然的轉動,原因有可能是什麼,我一開始以為是Transition-timing-function的問題,但好像不是。

iT邦新手 5 級 ‧ 2018-10-15 16:31:44 檢舉

啊哈 作者每堂課都會留一個問題要我們自己去想 這剛好就是他留的問題耶~
但慚愧了我還沒解 網路上有很多人是寫0秒的時候停止動畫
看很多人都成功但是我加上去後只是動的角度變小而已 還是會有不自然的轉動QQ

if (sec === 0) {
secHand.style.transition = 'all 0s';
} else {
secHand.style.transition = 'all 0.05s';}

smit iT邦新手 5 級 ‧ 2018-10-17 09:24:10 檢舉

我後來直接給他0s 看起來就正常了,不過作者會留一個問題,我倒是不知道,英文菜B也沒看到最後。/images/emoticon/emoticon02.gif

我要留言

立即登入留言