所以我目前有一个设计有两个主题的网站,布局完全相同,但许多元素在颜色和设计上发生了变化,以及显示了新的网站图像。我简单地通过创建两个 css 文件来实现这一点。默认布局被设置为所有访问者的样式,第二个是通过创建一个带有脚本的链接来实现的,通过单击它来切换应用于站点的 css,我将其创建为一个按钮,该按钮本身在 css 中专门设置了样式。这些按钮允许切换到第二个主题并返回到默认主题,无论选择的主题如何,这两个按钮都会显示。这些按钮彼此相邻,没有切换开关或图像或下拉列表,它们显示为两个链接。这是这些代码。
风格:
<link rel="stylesheet" href="blue.css">
按钮:
<button class="button2" onclick="toggleTheme('blue.css')">Blue</button> <button class="button2" onclick="toggleTheme('grey.css')">Grey</button>
我想解决的问题是,尽管单击将主题更改为“灰色”并更改了该页面上的主题,但一旦访问者单击另一个页面,它就会重置回默认蓝色,并且我想要主题除非访问者点击返回“蓝色”,否则就会留下来。我知道我需要为此编写一个脚本,但我没有找到解决方案,而且还遇到了许多教程说要使用 :root 来实现此目的,但我在 css 文件中进行了太多自定义更改,包括三种不同类型链接、四个标题、用于选择的自定义颜色和滚动条,发生了这么多事情,我不知道如果我更改 css 文件如何确保它正常工作。我认为脚本会让这个更容易实现。
老实说,我严重缺乏如何使用脚本的知识。即使我读到类似的问题,我也很困惑。
感谢您的帮助
这段代码有用吗?我该如何进行这项工作?当我添加脚本时,切换按钮根本不起作用。
<script>
// Function to toggle theme and save choice in sessionStorage
function toggleTheme(themeFileName) {
// Set the href attribute of the stylesheet to the chosen theme
document.getElementById('theme-style').setAttribute('href', themeFileName);
// Save the chosen theme in sessionStorage
sessionStorage.setItem('selectedTheme', themeFileName);
}
// Function to apply the theme from sessionStorage on page load
window.onload = function() {
// Check if a theme is stored in sessionStorage
var selectedTheme = sessionStorage.getItem('selectedTheme');
// If a theme is stored, apply it
if (selectedTheme) {
document.getElementById('theme-style').setAttribute('href', selectedTheme);
}
};
您在底部提供的代码有几个问题:
localStorage
,而不是sessionStorage
。会话存储似乎是用于会话的,顾名思义:DaddEventListener(...)
,而不是window.onload = ...
。因此,您可以有多个加载事件,并且客户端的脚本不会拦截您的网站代码。另外,当我读过你的帖子时,我认为你想修改另一个网站的样式。也许您有多个脚本文件,而其他某个脚本文件更改了主题?或者您需要在 CSS 样式表中的属性值之后放置
!important
(这样其他样式表就不会覆盖您的属性)?
顺便说一句,尝试在访客模式下查看您的网站。我的意思是,禁用扩展。也许您的某些扩展正在拦截您的代码。
我建议使用此代码:
/**
* Sets the theme to the specified one.
* @param {String} theme URL address to the CSS stylesheet of the theme.
*/
function toggleTheme(theme) {
document.querySelector("#theme-style").href = theme;
localStorage.setItem("theme", theme);
}
window.addEventListener("load", () => {
var theme = localStorage.getItem("theme");
if (theme)
document.querySelector("#theme-style").href = theme;
}, true);
对其功能的简要说明:与您的操作相同,但使用 localStorage。
对其作用的详细解释:
toggleTheme
更改href
元素的#theme-style
属性,然后还将localStorage中的theme
值设置为href
。href
元素的 #theme-style
属性更改为保存在 localStorage 中的属性(theme
项)。哦!我差点忘了。尝试使用开发人员工具(F12 / Ctrl+Shift+I)来调试您的网站。您可能想检查 Application 选项卡。它包含有关本地存储、会话存储、cookie 和许多其他内容的信息。