Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

CSS3变量

  • 定义

    element {
      --变量名: 变量值;
    }
    
    • 必须要用--开始,变量名对大小写敏感
    • 例子
      :root {
        --main-text-color: #333333;
      }
      
  • 使用

    .child {
      color: var(--main-text-color);
    }
    
    • 可以给var添加第二个参数,作为备用值
  • 使用js获取和动态改变这个变量的值

    const child = document.getElementById("child");
    //获取旧变量值
    let color = getComputedStyle(child).getPropertyValue("--main-text-color");
    console.log(color); // #333333
    
    //设置新的值
    child.style.setProperty("--color", "#666666");
    
    //获取新变量值
    color = getComputedStyle(child).getPropertyValue("--main-text-color");
    console.log(color); // #666666