Playing with CSS Variables and JS
Step 1. HTML
Step 2. 建立CSS變數,並套用
:root{
--base: #ffc600;
--spacing: 10px;
--blur: 10px;
}
img{
padding: var(--spacing);
background: var(--base);
filter: blur(var(--blur));
} h1{
color: var(--base);
}
✏️
:root{ }
最多的應用多是搭配 CSS 變數 ( CSS variables ) 來應用
Step 3. JS選取input元素
const inputs=document.querySelectorAll('.controls input');function handleUpdate(){
console.log(this.value);
}inputs.forEach(input=>input.addEventListener('change',handleUpdate)); //更改數值時觸發
inputs.forEach(input=>input.addEventListener('mouseover',handleUpdate));//滑鼠over時觸發
Step 4. 將數值組合成需要的內容
...
function handleUpdate(){
const suffix = this.dataset.sizing || ''; //抓到該值的單位
document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix)
}
...
dataset
:包含所有 data-sth 所設定的數值。const suffix = this.dataset.sizing || '';
:未避免沒有這個設定的狀況(例:顏色),所以要加上||''
this.name
:抓到的數值為 html中設定的 name
延伸資源:CSSStyleDeclaration.setProperty() — Web API 接口参考 | MDN
✏️ style.setProperty(propertyName, value, priority)
propertyName
:代表被更改的CSS屬性。
value
:含有新的屬性值。如果沒有指定,則為null。注意:
value
不能包含"!important"
,應該使用priority
參數.
priority
可選,允許設置 "important" CSS 優先級。如果沒有指定, 則當作null。