
這個章節,告訴我們該如何利用CSS變數(不是SASS)來調整圖片中黃框的pandding,邊框及JS字體顏色,以及模糊
:root {
        /* 設定CSS的變數 */
        --base: #ffc600;
        --spacing: 10px;
        --blur: 0px;
      }
我們打開範例檔,到CSS區塊時可以發現作者設定的CSS變數,在:root這個大括號裡面


當F12去用選擇器:root時顯示的是html,而且我們得知了:root及html選擇器選擇的是同一個區域,但是這兩個有什麼差別呢?
於是上網尋找到了他們之間的差異:
:root選擇器比html選擇器具有更高的權重。這是因為:root是偽類選擇器,html而是一個類型選擇器。這代表當我們同時設定了:root及html時,因為權重的關係:root會覆蓋html所設定的屬性:root {
  background-color: red;
}
html {
  background-color: blue;
}
/* HTML document   background-color 顯示的是紅色  */
 const inputs = document.querySelectorAll(".controls input");
  inputs.forEach(function (input) {
    input.addEventListener("change", changeHandler);
    input.addEventListener("mousemove", changeHandler); //加上移動的事件
 /***此為HTML*/**
 <input
        id="spacing"
        type="range"
        name="spacing"
        min="10"
        max="200"
        value="10"
        data-sizing="px"
      />
      <label for="blur">Blur:</label>
      <input
        id="blur"
        type="range"
        name="blur"
        min="0"
        max="25"
        value="0"
        data-sizing="px"
      />
      <label for="base">Base Color</label>
      <input id="base" type="color" name="base" value="#ffc600" />
const inputs = document.querySelectorAll(".controls input");
  inputs.forEach(function (input) {
    input.addEventListener("change", changeHandler);
    input.addEventListener("mousemove", changeHandler); //加上移動的事件
    
function changeHandler() {
    let unit = this.dataset.sizing || " "; 
    document.documentElement.style.setProperty(
      "--" + this.name, //設定CSS的屬性名稱
      this.value + unit
    );
  }
unit這個變數的賦值運用了短路求值計算,當觸發函式的時候我們的input中如果有自定義屬性dataset.sizing則取它的值,如果沒有則為空值
setPropertycolor、background-color 等),也可以用來設置自定義的 CSS 變數(如 --base)。我們可以利用此屬性,在監聽到input出現change及mousemove時更改我們變數的數值
用法像是這樣:
document.documentElement.style.setProperty( property, value);
document.documentElement.style.setProperty( 
 "--" + this.name, //設定CSS的屬性名稱
 this.value + unit 
    );