<button onclick="foo()">读取变量</button>
<button onclick="bar()">写入变量</button>
<button onclick="baz()">删除变量</button>

<div class="box">default</div>
<div class="box success">succes</div>
<div class="box error">error</div>
:root {
  --bg-color: burlywood;
}
body {
  background-color: var(--bg-color);
}


button {
  color: var(--bg-color);
  background-color: #000;
}

.box {
  width: 100px;
  height: 30px;
  --bg-color: #ccc;
  --border-color: #777;
  background: var(--bg-color) url('https://kano.guahao.cn/JsT348336686') no-repeat center / contain;
  border: 1px solid var(--border-color);
  &.success {
    margin-top: 10px;
    --bg-color: #f0f9ef;
    --border-color: #7ebb7a;
  }
  &.error {
    margin-top: 10px;
    --bg-color: #fff5f5;
    --border-color: #f78b8b;
  }
}
View Compiled
let n = 0
const colors = ['#fa0', '#8aa', 'yellowgreen', '#fff']

function foo() {
  alert(document.body.style.getPropertyValue("--bg-color"))
}
function bar() {
  document.body.style.setProperty("--bg-color", colors[n%colors.length])
  n++
}
function baz() {
  document.body.style.removeProperty("--bg-color")
}
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.