为什么不能更新 css 变量名来应用不同的颜色主题?

Why can't update css variable name to apply a different color theme?

我想通过 javascript.[=14= 更改单个自定义变量,在 scss 内置的 else/if 语句中的两个 css 主题之间切换]

我看到很多关于如何通过 javascript 更改 css 变量中的一种或两种颜色的示例,但我想通过更改 $theme 变量来更改网站的整个主题只要。

查看codepen:https://codepen.io/roroland/pen/gVWLBm

// Var defaults
$theme: default;
$primary: null;
$warn: null;
:root {
  --theme: #{$theme};
}

// If theme is 'default' use this
@if ( $theme == "default") {
  $primary: orange;
  $warn: purple;
}
// If theme is 'other' use this instead
@elseif($theme == "other") {
  $primary: black;
  $warn: blue;
}

p {
  display: block;
  padding: 2rem;
  color: $primary;
  background: $warn;
}

JS

document.documentElement.style.setProperty('--theme', "other");

如果我尝试更新 $theme 它不起作用,我尝试使用和不使用插值,设置 'null' 主题变量等。它只是忽略了 JS 指令。

有人可以解释为什么不起作用吗? 谢谢

我认为你正在尝试做的事情无法完成。

SCSS 是在服务器端运行的 CSS 预处理器。它会编译成 CSS 然后在客户端(浏览器)呈现。而一旦编译成CSS,所有的SCSS变量都没有了(因为浏览器只能渲染CSS)。

您正在编写的JS正在浏览器(客户端)中执行。

所以,如果你想这样做,你需要

  • 将 类 分配给元素并设置它们的样式。然后,使用 JS
  • 更改 Class
document.getElementById("MyElement").className = "other-theme";
document.getElementById("MyElement").className = "default-theme";

并且在CSS,

.other-theme{
color: orange;
background: purple;
}

.default-theme{
color: black;
background: blue;
}

您可以使用 SCSS 生成此 CSS 样式。

  • 或者,您可以使用 AJAX 的方法将请求发送到 服务器并获取更新后的样式 sheet.

我认为您应该通过添加事件侦听器并切换 class(有两个不同的 classes)[=11 来实现 javascript 而不是复杂的 css =]

这 link 可能会有所帮助

https://www.w3schools.com/howto/howto_js_toggle_class.asp

这是 CSSVariables(动态)的工作,不像 Sass 变量(静态)在 运行 时工作。

/* toggle theme class */
addEventListener('click', e => {
  document.documentElement.classList.contains('other') ?
    document.documentElement.classList.remove('other') :
    document.documentElement.classList.add('other');
})
/* default theme */
:root {
  --primary: orange;
  --warn: purple;
}

/* other theme */
:root.other {
  --primary: black;
  --warn: blue;
}

p {
  display: block;
  padding: 2rem;
  /* use theme colors */
  color: var(--primary);
  background: var(--warn);
}
<h2>Click to toggle theme class</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Distinctio dolorem quas quod eaque voluptatem error, rem vero non. Eveniet maxime saepe fugiat tenetur dignissimos enim, provident earum illo quasi fugit?</p>