【发布时间】:2021-10-19 12:47:27
【问题描述】:
我开始使用 Hugo、SCSS 和 JS 为我的网站实现暗模式切换。
到目前为止,我为“light”和“dark”两种主题模式创建了一个映射,并在我的其他 scss 文件中使用了它们与 @include
现在所有单独的颜色都可以通过切换器正常切换,除了我的背景颜色。到目前为止找不到任何解决方案,但也许我必须以某种方式干扰 Bootstraps JS?有什么想法吗?
SCSS
$primary-font: "Raleway", sans-serif;
$icon-font: "themify";
// Color Variables
$primary-color: #3787b3;
$black: #000;
$white: #fff;
$gray: #f4fcff;
$themes: (
darkTheme: (
'bg-color': #222222,
'text-color': #ffffff,
'text-color-dark': #c9c9c9,
'text-color-light': #ffffff,
'body-color': #3b3d42,
'border-color': #4a4b50
),
lightTheme: (
'bg-color': #fff,
'text-color': #666666,
'text-color-dark': #222222,
'text-color-light': #959595,
'body-color': #fff,
'border-color': #acb9c4
)
);
@mixin theme() {
@each $theme, $map in $themes {
$theme-map: $map !global;
.#{$theme} & {
@content;
}
}
$theme-map: null !global;
}
@function theme-get($key) {
@return map-get($theme-map, $key);
}
body {
@include theme(){
background-color: theme-get('bg-color');
}
overflow-x: hidden;
}
JS
//theme-toggler
const getTheme = window.localStorage && window.localStorage.getItem("theme");
const themeToggle = document.querySelector(".theme-toggle");
const isDark = getTheme === "dark";
if (getTheme !== null) {
document.body.classList.toggle("darkTheme", isDark);
}
themeToggle.addEventListener("click", () => {
document.body.classList.toggle("darkTheme");
window.localStorage &&
window.localStorage.setItem(
"theme",
document.body.classList.contains("darkTheme") ? "dark" : "light"
);
});
console.log()
HTML
<!DOCTYPE html>
<html lang="{{ with .Site.LanguageCode }}{{ . }}{{ else }}en-US{{ end }}">
{{- partial "head.html" . -}}
<body>
{{- partial "preloader.html" . -}}
{{- partial "header.html" . -}}
{{- block "main" . }}{{- end }}
{{- partial "footer.html" . -}}
</body>
</html>
【问题讨论】:
-
你试过@media (prefers-color-scheme: dark) {} 吗?
-
嘿,裁缝,不知道这对我有什么帮助。我正在寻找更多默认的轻主题,如果用户想要他/她可以使用切换(切换器)按钮切换主题模式。 @media 链接到浏览器首选项还是我错了? developer.mozilla.org/en-US/docs/Web/CSS/@media/…
-
是的,你是对的。您能否制作一个 codepen 或其他东西,以便代码易于测试?
标签: javascript sass hugo