Tweety-666
    • 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
    • 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
    • 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 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
  • 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
    # 【JS30】Day3 - Playing with CSS Variables and JS ## 怎麼做出瀏覽器中的"調整器" ###### tags: `CSS變數`、`data-*`、`style.setProperty`、`this` 本章節畫面中的顏色選擇器、模糊度選擇器,都是透過input做的。當然還要搭配函式。 ```javascript <div class="controls"> <label for="spacing">Spacing:</label> <input id="spacing" type="range" name="spacing" min="10" max="200" value="10" data-sizing="px"> <label for="blur">Blur:</label> <input id="blur" type="range" name="blur" min="0" max="25" value="10" data-sizing="px"> <label for="base">Base Color</label> <input id="base" type="color" name="base" value="#ffc600"> </div> ``` 上方程式碼中的```type="range"```、```type="color"```,決定了[iuput的樣式](https://www.w3schools.com/tags/att_input_type.asp),最常見的input當然是輸入的欄位。 --- ## CSS變數觀念 以前在寫CSS的時候,還沒有CSS變數的觀念,當我想要改某個東西,就用編輯器選取要改的,再按ctrl+D,一次選起來改完。後來看了[這篇](https://medium.com/hulis-blog/frontend-engineer-guide-297821512f4e),才知道可以把CSS設成變數,要改的話改變數就好了! 但CSS預處理器已經把變數處理好後,靜態網頁是無法再改變變數的。簡單來說,要在瀏覽器改變CSS變數,就用原生的寫法。 利用 :root{--<varName>: <varValue>}建立CSS變數,並且在CSS屬性值中使用 var(--<varName>) 來代入變數的值: ```css :root { --base: #ffc600; --spacing: 10px; } img { display:block; box-sizing: border-box; margin: 0 auto; padding: var(--spacing); background: var(--base); } ``` --- ## 用JS改變CSS變數 1.先選取DOM是必要的。下方程式碼已經把全部的input選起來。 2.當這些DOM改變後,執行函數。 3.定義函數。 ```javascript <script> const inputs = document.querySelectorAll('.controls input'); inputs.forEach(input => input.addEventListener('change', handleUpdate)); inputs.forEach(input => input.addEventListener('mousemove', handleUpdate)); function handleUpdate() { const suffix = this.dataset.sizing || ''; document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix); } </script> ``` 這邊,我們要讓調整器被改變時,觸發一些行為(函式)。所以要先定義調整器的DOM。**想法是:讓每個調整器都可以被個別觸發;而不是只碰一個調整器,全部的調整器都被觸發。** ![](https://i.imgur.com/z40TCTo.png) console一下(如上圖),會發現```document.querySelectorAll('.controls input')```裡面有個_proto_顯示為nodeList,點開會看到forEach,而更內層的_proto_顯示的是Object(物件)。 奇怪,怎麼會有forEach的用法,難道inputs是陣列嗎? **這看起來像是陣列,但其實不是。所以這個偽陣列中沒有陣列的全部用法(像是.map)**。查閱"偽陣列"可以發現很多轉換成陣列的資料。 也可以將此轉換成陣列,但沒有必要,因為已經可以用forEach這個方法了,除非使用的是不支援的舊瀏覽器。 --- ## data-* ```javascript function handleUpdate() { const suffix = this.dataset.sizing || ''; document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix); ``` suffix是字尾的意思。這裡用到了[dataset](https://developer.mozilla.org/zh-TW/docs/Web/API/HTMLElement/dataset)這個神奇的東西。 開發者可以自訂dataset,在html檔案中取名為data-* ;用DOM時,可以用.dataset來取用。 ```*```這部分可以取名字。好比說:data-content、data-index。 可是dataset要用來做什麼呢?dataset可以自定義屬性,用自定義屬性,來進行一些數據的存放。 這裡的```this.dataset.sizing```,```dataset.sizing```就是自定義資料```data-sizing```,也就是調整器的數值。 並加上 ```|| ' '``` ,因為不是每個調整器都有字尾,blur大小的調整器有px,但顏色調整器就沒有,所以沒有字尾就給空字串。 ## this是什麼?為什麼要加上它? [this是什麼](https://translate.google.com.tw/translate?hl=zh-TW&sl=zh-CN&u=https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this&prev=search)?簡單來說,在函數內部, this的值取決於函數被調用的方式。 為什麼要加上它? 因為上方程式中,DOM抓取了全部的input,但我只需要我點選的"這個"input被觸發就好,而不是全部的input被觸發。 --- ## style.setProperty 搞定DOM後,處理函式吧。 ```javascript function handleUpdate() { const suffix = this.dataset.sizing || ''; document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix); ``` ```document.documentElement```,這個```documentElement```屬性可返回文檔的根節點。這邊讓我困惑一下子,documentElement是為了抓取html上的節點。針對抓到的節點去賦予屬性、屬性值,並加上字尾。 ```style.setProperty```,顧名思義在style設置Property,Property是css中,選擇器的屬性。 ```css .someClass{ color:white; property:propertyName; } ```

    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