Try   HackMD

手動選擇顏色及調整數值的圖片(CSS Variables)

版型

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

<div class="controler"> <label for="spacing">Spacing : </label> <input type="range" name="spacing" min="10" max="200" value="10"> <label for="blur">Blur : </label> <input type="range" name="blur" min="0" max="25" value="10"> <label for="color">Color : </label> <input type="color" name="color" value="#ffc660"> </div>

如何運行

:root

:root 沒看到有太多的應用,但是最多的應用多是搭配 CSS 變數 ( CSS variables ) 來應用

建立變數

使用兩個減號開始
:root 可以在整個頁面上使用,如果要指定特定的 class 也可以

:root { --color: #ffc660; --spacing: 10px; --blur: 10px; }

套用變數

  1. 範例

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  2. 用 svg 放到 vscode ,抓出他的 svg path ,找到想要替代的顏色也可以成功

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

監聽

const inputs = document.querySelectorAll('.controler input') console.log(inputs) inputs.forEach((item) => { // 改變就會監聽 item.addEventListener('change', function(e) { console.log('target', this.value) }) // 移動也會監聽 item.addEventListener('mousemove', function(e) { console.log('mousemove target', this.value) }) })

接尾詞 suffix

在 html 裡面設定 dataset ,把他的單位加在裡面(ex: px, deg) 顏色不用

<div class="controler"> <h1>CSS Variables</h1> <label for="move">Move : </label> <input type="range" name="move" min="10" max="200" value="10" data-suffix="deg"> <label for="blur">Blur : </label> <input type="range" name="blur" min="0" max="25" value="10" data-suffix="px"> <label for="color">Color : </label> <input type="color" name="color" value="#ffc660"> </div>

const suffix = this.dataset.suffix || ''
如果有 dataset 的話抓出,或空字串(因為顏色不會有單位)

接著要找到 input 設定的名稱 name (這邊設定的 name 跟 css :root 裡面的名稱是設定一樣的)
console.log(this.name)

setProperty 設定屬性值

style.setProperty(propertyName, value, priority);
https://developer.mozilla.org/zh-CN/docs/Web/API/CSSStyleDeclaration/setProperty

document.documentElement.style.setProperty(`--${this.name}`,this.value + suffix)
tags: JS

最後,親愛的大家!我需要你的大聲鼓勵 ٩(⚙ᴗ⚙)۶

如果覺得這篇文章對你有幫助,請給我個一個小小的鼓勵 ❤ 讓我知道,這會成為我寫下去很大的動力。
對了,我還有其他文章,如果有興趣也來逛逛吧!
(文章中如有覺得不妥之處、錯誤內容,也可以透過聯絡我,我會儘速改善,感謝!)

☞ YoJanni 珍妮 2021 正在設計轉職前端的路上,希望大家在學習的路上能夠一起成長
☞ 聯絡我