Javascript 如何使用water.css在明暗模式之间切换
我在我的网站中使用water.css,我有以下js代码:Javascript 如何使用water.css在明暗模式之间切换,javascript,html,css,Javascript,Html,Css,我在我的网站中使用water.css,我有以下js代码: function setTheme(themeName) { localStorage.setItem('theme', themeName); document.documentElement.className = themeName; } // function to toggle between light and dark theme function toggleTheme() { if (localS
function setTheme(themeName) {
localStorage.setItem('theme', themeName);
document.documentElement.className = themeName;
}
// function to toggle between light and dark theme
function toggleTheme() {
if (localStorage.getItem('theme') === 'theme-dark') {
setTheme('theme-light');
} else {
setTheme('theme-dark');
}
}
// Immediately invoked function to set the theme on initial load
(function () {
if (localStorage.getItem('theme') === 'theme-dark') {
setTheme('theme-dark');
} else {
setTheme('theme-light');
}
})();
此按钮用于切换:
<div class="container">
<h1>Theme Switcher</h1>
<button id="switch" onclick="toggleTheme()">Switch</button>
</div>
主题切换器
转换
我导入了javascript文件,我想知道如何更改javascript代码以在2个cdn链接之间切换:
及
2.water.css
以下是更改主题的方法:
html
我在setTheme
函数中进行了更改:
var link = document.createElement('link');
link.rel = 'stylesheet';
if (themeName == "theme-dark") {
link.href = 'https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/dark.min.css';
} else {
link.href = 'https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/light.min.css';
}
document.head.appendChild(link);
这会根据主题添加相关的css
是一个JSFIDLE实时演示。当用户单击“上一步”按钮时,它不会保存主题。@Liel我已经对它进行了测试,它确实保存了主题,肯定还有其他问题。
function setTheme(themeName) {
localStorage.setItem('theme', themeName);
//document.documentElement.className = themeName;
var link = document.createElement('link');
link.rel = 'stylesheet';
if (themeName == "theme-dark") {
link.href = 'https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/dark.min.css';
} else {
link.href = 'https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/light.min.css';
}
document.head.appendChild(link);
}
// function to toggle between light and dark theme
function toggleTheme() {
if (localStorage.getItem('theme') === 'theme-dark') {
setTheme('theme-light');
} else {
setTheme('theme-dark');
}
}
// Immediately invoked function to set the theme on initial load
(function() {
if (localStorage.getItem('theme') === 'theme-dark') {
setTheme('theme-dark');
} else {
setTheme('theme-light');
}
})();
var link = document.createElement('link');
link.rel = 'stylesheet';
if (themeName == "theme-dark") {
link.href = 'https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/dark.min.css';
} else {
link.href = 'https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/light.min.css';
}
document.head.appendChild(link);