做一個"brand spanking new"的CSS, 這裡的「CSS變數」不是Sass的變數功能。畫面有三個變數: Space, Blur, Base Color,當我們在畫面設定值(拉動range或改變顏色),它會立即的更新畫面
- 功能
- 用CSS變數
- 追加
- 練習「設定區域變數」
- 畫面
- 改變控制項、立即改變畫面
CSS變數可以被Javascript更新, 也就是當你可以在頁面上任何地方更新CSS變數, 變數就可以自動更新。
我知道你會說「wes, we've had variables in SASS forever and this not new」
在SASS, 你可以定義、編譯,在變譯之後將無法再改變變數(們)
- brand spanking new 意思是 "Entirely new"(全新的)
- smart Alec 意思是 「自以為是,自作聰明的人」
在HTML裡嵌入自定義的color資料
<tagName data-color></tagName>
在Javascript取出來的方法,在element取dataset就可以用相同的「自定義名稱」讀/寫 自定義資料了,資料型態是字串。
tagNameElement.dataset.color = "";
jsref: The CSSStyleDeclaration Object
setProperty(property, value, priority)設定CSS的屬性給element(直接加在style="")
使用兩個-符號,代表「變數」
自定義變數名稱--main-bg-color, 值brown
element {
--main-bg-color: brown;
}
element.style.setProperty('--main-bg-color', 'brown');
使用var()代表「使用變數」,並且將「宣告名稱」丟進來
將變數--main-bg-color給定進background-color
element {
background-color: var(--main-bg-color);
}
用CSS的:root選擇器,可以選到JS的document.documentElement
在HTML中,root element就是<html>
CSS這樣宣告
:root {
--base: #ff6c00;
--spacing: 10px;
--blur: 10px;
}
JS就可以這樣改寫
document.documentElement.style.setProperty(`--${this.name}`, this.value);
jsref: The HTML DOM Document Object
document.documentElement回傳<html>的節點