切换我网站的主题
Switching theme of my website
我希望允许用户通过按下按钮来切换我网站的整个配色方案。
我有 2 个单独的 .less 文件,它们具有相同的全局变量,但颜色不同。问题看起来很简单.. "swap 1 .less file for the other"。但我该如何真正做到这一点?
当然,我可以根据单例状态在 .js 中逐个元素地更改整个站点,但这似乎是胶带解决方案。
一个可能的解决方案示例:假设您有一个 div
元素,您希望在每个主题中为其背景着色不同。加载两个 .less
文件并像这样编辑它们(将主题 class 添加到包装整个文档的 body
元素):
主题-1.less
body.theme-1 {
div.address {
background-color: yellow;
}
}
主题-2.less
body.theme-2 {
div.address {
background-color: fuchsia;
}
}
然后提供一种机制供用户更改主题(例如下拉菜单)。当用户从菜单中选择时 - 例如从 theme-1
更改为 theme-2
- 发出此 JS:
document.getElementsByTagName("body")[0].classList.replace("theme-1", "theme-2");
一般来说,您可以通过不止一种方式来做到这一点:
document.getElementsByTagName("body")[0].classList.replace(<currently-selected-theme>, <newly-selected-theme);
或
document.getElementsByTagName("body")[0].classList.remove(<currently-selected-theme>).add(<newly-selected-theme>);
我希望允许用户通过按下按钮来切换我网站的整个配色方案。
我有 2 个单独的 .less 文件,它们具有相同的全局变量,但颜色不同。问题看起来很简单.. "swap 1 .less file for the other"。但我该如何真正做到这一点?
当然,我可以根据单例状态在 .js 中逐个元素地更改整个站点,但这似乎是胶带解决方案。
一个可能的解决方案示例:假设您有一个 div
元素,您希望在每个主题中为其背景着色不同。加载两个 .less
文件并像这样编辑它们(将主题 class 添加到包装整个文档的 body
元素):
主题-1.less
body.theme-1 {
div.address {
background-color: yellow;
}
}
主题-2.less
body.theme-2 {
div.address {
background-color: fuchsia;
}
}
然后提供一种机制供用户更改主题(例如下拉菜单)。当用户从菜单中选择时 - 例如从 theme-1
更改为 theme-2
- 发出此 JS:
document.getElementsByTagName("body")[0].classList.replace("theme-1", "theme-2");
一般来说,您可以通过不止一种方式来做到这一点:
document.getElementsByTagName("body")[0].classList.replace(<currently-selected-theme>, <newly-selected-theme);
或
document.getElementsByTagName("body")[0].classList.remove(<currently-selected-theme>).add(<newly-selected-theme>);