竹白
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Day2: JS and CSS Clock [竹白記事本](https://chupainotebook.blogspot.com/),Javascript 30,紀錄。 ###### tags: `Javascript 30` ## 實現效果 用 JS 與 CSS 搭配製作一個實時的時鐘效果。 - [原始碼](https://github.com/chupai/JS30/tree/master/source_code/Day02) - [原始狀態](https://chupai.github.io/JS30/source_code/Day02/index-START.html) - [範例效果](https://chupai.github.io/JS30/source_code/Day02/index-FINISHED.html) ## 重點 - 建立指針 CSS 樣式 - 取得指針 DOM - 建立控制時鐘函式 - 取得現在時間 - 控制 DOM 樣式 - 建立計時器重複執行函式 ## 基礎語法 ### JavaScript - [`Date` 物件](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Date) - [`getHours()`](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours) - [`getMinutes()`](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Date/getMinutes) - [`getSeconds()`](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Date/getSeconds) ### BOM - [`setInterval`](https://developer.mozilla.org/zh-CN/docs/Web/API/Window/setInterval) 計時器 ## 說明 ### 1. 將指針原始樣式改成 12 點鐘方向 課程提供的原始 CSS,在計算角度時,要補 90度,因此這邊會稍作修改。 ### 2. 計算角度 一個圓有 360 度: - 60 秒 - 360 / 60 = 6 - 每秒轉 6 度 - 60 分鐘 - 360 / 60 = 6 - 每分鐘轉 6 度 - 12 個小時 - 360 / 12 = 30 - 每一小時轉 30 度 ## 實作 ### 1. 步驟 #### Step 1  調整 CSS 在 `.clock-face` 新增一個中心點方便定位。 ```css .clock-face::after { content: ''; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); border-radius: 50%; background-color: white; width: 10px; height: 10px; } ``` 將原本的 `.hand` 改掉, ```css .hand { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } ``` 新增 `.hour-hand` `.min-hand` `.second-hand`: 我們將指針的樣式寫在偽元素,這樣旋轉容器時,就會以中心旋轉。 並且將指針起點改成 12 點鐘方向,這樣就不用額外計算多出來的角度。 ```css .hour-hand::after { position: absolute; content: ''; width: 10px; height: 100px; background-image: linear-gradient(black 50%, transparent 50% 100%); } .min-hand::after { position: absolute; content: ''; width: 10px; height: 200px; background-image: linear-gradient(black 50%, transparent 50% 100%); } .second-hand::after { position: absolute; content: ''; width: 4px; height: 160px; background-image: linear-gradient(black 50%, transparent 50% 100%); } ``` #### Step 2  取得指針的 DOM 物件 ```javascript const hour = document.querySelector('.hour-hand'); const min = document.querySelector('.min-hand'); const second = document.querySelector('.second-hand'); ``` #### Step 3 建立函式 `setClock()` ```javascript function setClock() { const now = new Date(); let hourDeg = now.getHours() * 30; let minDeg = now.getMinutes() * 6; let secondDeg = now.getSeconds() * 6; hour.style.transform = `rotate(${hourDeg}deg)`; min.style.transform = `rotate(${minDeg}deg)`; second.style.transform = `rotate(${secondDeg}deg)`; } ``` JavaScript 的 Date 物件只能以建構式的方式來產生,因此這裡用到 `new` 關鍵字,取得現在時間。 分別取得秒、分、時的時間,並計算角度,用來控制指針的旋轉度數。 #### Step 4 呼叫函式並加上計時器 ```javascript setClock(); // 初始化畫面 setInterval(setClock, 1000); ``` `setInterval` 計時器,可以設定每隔一段時間重複執行,這裡設 1 秒。 另外關於畫面顯示的計時器也可以使用 [`requestAnimationFrame`](https://developer.mozilla.org/zh-TW/docs/Web/API/Window.requestAnimationFrame),它會跟據硬體的效能來控制更新頻率,簡單來說就是會以你硬體能顯示最大 FPS 來刷新頻率。 目前已完成初步功能。 #### Step 5 微調 由於現實中指針不會是時間一到就直接跳到下一格,因此這裡的時針與分針還需要補上一些細節。 - 時針 - 每小時一格有 30 度 - 一小時有 60 分鐘 - 因此角度還要加上「目前幾分 \* (30 / 60)」 - 分針 - 每分鐘有 6 度 - 每分鐘有 60 秒 - 因此角度還要加上「目前幾秒 \* (6 / 60)」 稍作微調程式碼: ```javascript let secondDeg = now.getSeconds() * 6; let minDeg = now.getMinutes() * 6 + now.getSeconds() * (6 / 60); let hourDeg = now.getHours() * 30 + now.getMinutes() * (30 / 60); ``` #### Step END ```javascript (function() { const hour = document.querySelector('.hour-hand'); const min = document.querySelector('.min-hand'); const second = document.querySelector('.second-hand'); function setClock() { const now = new Date(); let secondDeg = now.getSeconds() * 6; let minDeg = now.getMinutes() * 6 + now.getSeconds() * (6 / 60); let hourDeg = now.getHours() * 30 + now.getMinutes() * (30 / 60); second.style.transform = `rotate(${secondDeg}deg)`; min.style.transform = `rotate(${minDeg}deg)`; hour.style.transform = `rotate(${hourDeg}deg)`; } setClock(); // 初始化畫面 setInterval(setClock, 1000); })(); ``` ### 2. 實作連結 - [初版](https://chupai.github.io/JS30/source_code/Day02/index1.html) - [美化](https://chupai.github.io/JS30/source_code/Day02/index.html)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully