我想在刷新页面以及所有其他页面时保留所选主题.我见过其他例子,但我不知道如何在代码中实现它,因为我是个新手.到目前为止,我已经包含了该功能的代码.非常感谢.
function changeTheme(bgColor, textColor) {
var styles = document.documentElement.style;
styles.setProperty('--bg-color', bgColor);
styles.setProperty('--text-color', textColor);
}
var dark = document.querySelector('#dark');
var light = document.querySelector('#light');
var blue = document.querySelector('#blue');
dark.addEventListener('click', function() {
changeTheme('#333', 'white');
});
light.addEventListener('click', function() {
changeTheme('white', 'black');
});
blue.addEventListener('click', function() {
changeTheme('#2982F5', 'white');
});
:root {
--bg-color: #333;
--text-color: white;
}
body {
font-family: sans-serif;
background: #c0c0c0;
}
nav {
color: var(--text-color);
background: var(--bg-color);
}
ul {
display: flex;
justify-content: center;
align-items: center;
list-style-type: none;
}
li {
margin-left: 15px;
}
a {
color: var(--text-color);
}
<nav>
<ul>
<p>Select theme:</p>
<li>
<a href="#" id="dark">Dark</a>
</li>
<li>
<a href="#" id="light">Light</a>
</li>
<li>
<a href="#" id="blue">Blue</a>
</li>
</ul>
</nav>