[筆記]JavaScript30學習-Day3

Lisa Li
木棉草工作室
Published in
3 min readOct 7, 2020

2020.10.07

學習網站:javascript30

僅記錄JS及較複雜的CSS部分,若有不清楚或是歡迎留言討論,
謝謝(´。• ω •。`)

Playing with CSS Variables and JS

Step 1. HTML

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 根目錄選取器 — 叫你阿爸出來講

✏️ :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。

--

--