javascript - SCSS data-theme="dark" 变量不加载
问题描述
我目前正在为我的网站使用暗模式,并且 JS 工作正常,它将data-theme="dark"
参数添加到 html 标记并将其存储在本地存储中。但是 SCSS 中的变量不会加载。这是我的代码:
$colorMain: #9C27B0;
$colorDisabled: rgb(92, 92, 92);
$colorTextWhite: #FFF;
$colorTextBlack: #000;
$colorTextTitle: #2b2b2b;
$colorTextPara: #4e4e4e;
$colorBgMain: #FFF;
$colorBgSec: darken($colorBgMain, 3%);
$colorAlertSuccess: #8BC34A;
$colorAlertDanger: #F44336;
$colorDarkMode: #272727;
[data-theme="dark"] {
$colorMain: rgb(176, 39, 39);
$colorDisabled: rgb(92, 92, 92);
$colorTextWhite: #FFF;
$colorTextBlack: #000;
$colorTextTitle: #2b2b2b;
$colorTextPara: #4e4e4e;
$colorBgMain: rgb(0, 0, 0);
$colorBgSec: darken($colorBgMain, 3%);
$colorAlertSuccess: #8BC34A;
$colorAlertDanger: #F44336;
$colorDarkMode: #ffffff;
}
JS:
const toggleSwitch = document.querySelector('input[name="mode"]');
function switchTheme(e) {
if (e.target.checked) {
trans()
document.documentElement.setAttribute('data-theme', 'dark');
localStorage.setItem('theme', 'dark'); //add this
} else {
trans()
document.documentElement.setAttribute('data-theme', 'light');
localStorage.setItem('theme', 'light'); //add this
}
}
toggleSwitch.addEventListener('change', switchTheme, false);
const currentTheme = localStorage.getItem('theme') ? localStorage.getItem('theme') : null;
if (currentTheme) {
document.documentElement.setAttribute('data-theme', currentTheme);
if (currentTheme === 'dark') {
toggleSwitch.checked = true;
}
}
let trans = () => {
document.documentElement.classList.add('transition');
window.setTimeout(() => {
document.documentElement.classList.remove('transition');
}, 1000)
}
有人可以帮助我吗?:D
解决方案
变量不能只是加载,你必须使用一些预处理库来转换它们。或者,如果它适合您的用例,我建议您使用 css 变量。
看这篇文章的第二个实现。我已经测试了代码,它应该适合你。干杯:)
推荐阅读
- python - 由于 CUDA 错误,无法从 Keras 模型进行预测
- java - 如何从字符串中取出数字并消除这些数字并存储过滤后的字符串并在java中打印
- python - Python 位支持以提高可读性(如果可能)
- codeigniter - Capcha 图像使用 codeigniter 显示为空白
- sqlite - 如何制作动态的计算列?(斯威夫特,SQLite)
- ansible - Ansible 2.9.8 - 将变量传递给 ansible.cfg
- selenium - 从python Selenium webscraping中的同一页面弹出窗口中提取信息
- android - 在后台接收位置更新的最佳方式是什么?
- typescript - 将多个字符串标签和数组保存到打字稿中的关联数组
- php - 使用预签名 URL 限制对 S3 上静态站点的访问?