我在我的网站中使用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 (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链接之间切换:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/dark.min.css">
和 2. water.css
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/light.min.css">
答案 0 :(得分:1)
以下是更改主题的方法:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="container">
<h1>Theme Switcher</h1>
<button id="switch" onclick="toggleTheme()">Switch</button>
</div>
</body>
</html>
javacript
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');
}
})();
我在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 。
Here是一个JSFiddle实时演示。