gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:18:50 26 4
gpt4 key购买 nike

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

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

查看代码笔: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更改类
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 方法将请求发送到服务器并获取更新后的样式表。

关于javascript - 为什么不能更新 css 变量名来应用不同的颜色主题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57281811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com