[JS30] Day03: Playing with CSS Variables and JS
HTML
我們可以用type
屬性來變化 input 元素,range
會出現進度條,color
會出現調色盤,label 元素的for
對應input
的id
屬性,為該 input 的標籤,對應到時點擊標籤等於點擊到 input。
<label for="spacing">Spacing:</label>
<input
id="spacing"
type="range"
name="spacing"
min="10"
max="200"
value="10"
data-sizing="px"
/>
<label for="base">Base Color</label>
<input id="base" type="color" name="base" value="#ffc600" />
CSS
我們要學習如何在 CSS 內創造變數(--variable)。
root可以選取到一份文件樹的根,我們定義以下變數讓其他元素使用,img 使用變數像是var(--base)
來改變背景顏色。
:root {
--spacing: 10px;
--blur: 10px;
--base: #ff4a00; /* yellow color */
}
img {
padding: var(--spacing);
filter: blur(var(--blur));
background: var(--base);
}
JavaScript
我們有三個 input 要選取,可以透過document.querySelectorAll
來選取到,特別注意的是選取到的結果會被存成一個NodeList,與一般的 Array 差別在於 Array 有的方法(method)更為多樣,超過 20 種;而 NodeList 有的種類較少: entries, forEach, items, keys 等等,所以有時候會看到人們把 NodeList 轉成 Array 去操作。
我們利用forEach
在每個 input 都加上change
跟mousemove
的監聽器,觸發時會啟動 handleUpdate 函式。
handleUpdate 函式中,我們透過setProperty
來改變 CSS Variable,document.documentElement
為整份文件,透過我點選取到的 input(this)的name
和value
來設定新的變數值。
新的變數值有些必須包括 suffix(後綴詞),在 spacing 和 blur 的 input 之中,透過dataset儲存,如果有sizing
便加上去,不然就加上空字串。
const inputs = document.querySelectorAll("input");
console.log(inputs); // NodeList
function handleUpdate() {
const suffix = this.dataset.sizing || "";
document.documentElement.style.setProperty(
`--${this.name}`,
this.value + suffix
);
}
inputs.forEach((input) => {
input.addEventListener("change", handleUpdate);
input.addEventListener("mousemove", handleUpdate);
});