CSS变量-交换值?

Ari*_*reu 4 css swap css-variables

我有一个非常简单的CSS变量问题。我想交换两个CSS变量,基本上等同[a, b] = [b, a]于ES6中的CSS变量。这是一个简单的例子:

<p>White background</p>
<button>Black background</button>
<div>
  <p>Black background</p>
  <button>White background</button>
</div>
Run Code Online (Sandbox Code Playgroud)
:root {
  --primary-color: #fff;
  --secondary-color: #000;
}

body {
  background-color: var(--primary-color);
}

button {
  background-color: var(--secondary-color);
}

div {
  /* i'd like to do the following: */
  --primary-color: var(--secondary-color);
  --secondary-color: var(--primary-color);

  /* so here, `--primary-color` would be `--secondary-color` from `:root`
   * and any children have these colors swapped as well
   */
  background-color: var(--primary-color);
}
Run Code Online (Sandbox Code Playgroud)

但是,这失败了,因为CSS var()是实时绑定。我在这里想念什么吗?还是这是规范当前的工作方式?

Tem*_*fif 5

您创建循环依赖项是因为您要使用另一个属性来定义每个属性,而这将无法正常工作。相反,您可以通过引入更多变量来尝试类似的操作:

:root {
  --p:#fff;
  --s:#000;
  --primary-color: var(--p);
  --secondary-color: var(--s);
}

body {
  background-color: var(--primary-color);
}

button {
  background-color: var(--secondary-color);
}

div {
  /* i'd like to do the following: */
  --primary-color: var(--s);
  --secondary-color: var(--p);
  
  background-color: var(--primary-color);
}
Run Code Online (Sandbox Code Playgroud)
<p>White background</p>
<button>Black background</button>
<div>
  <p>Black background</p>
  <button>White background</button>
</div>
Run Code Online (Sandbox Code Playgroud)