# 手動選擇顏色及調整數值的圖片(CSS Variables) ## 版型 ![](https://i.imgur.com/wpA6Rgx.png) ```htmlembedded= <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 也可以 ```css= :root { --color: #ffc660; --spacing: 10px; --blur: 10px; } ``` #### 套用變數 1. 範例 ![](https://i.imgur.com/if7IF8v.png) 2. 用 svg 放到 vscode ,抓出他的 svg path ,找到想要替代的顏色也可以成功 ![](https://i.imgur.com/NbnaTPM.png) ### 監聽 ```javascript= 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...) 顏色不用 ```htmlmixed= <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 ```javascript= document.documentElement.style.setProperty(`--${this.name}`,this.value + suffix) ``` ###### tags: `JS` {%hackmd @unayojanni/H1Qq0uKkK %}