我不太清楚如何将暗/亮模式的选择保存为 cookie。
这是我正在尝试的网页: https ://schooloffish.info/index.html
尝试了 cookie 的 w3schools 代码,但我无法让它工作。任何帮助表示赞赏。
我不太清楚如何将暗/亮模式的选择保存为 cookie。
这是我正在尝试的网页: https ://schooloffish.info/index.html
尝试了 cookie 的 w3schools 代码,但我无法让它工作。任何帮助表示赞赏。
使用document.cookie
:
// inside your event listener on the dark mode toggle:
document.cookie = "darkMode=true";
然后,您可以使用getCookie()之类的库存辅助函数来检索值:
let darkMode = getCookie("darkMode");
您可以使用localStorage
css 变量来存储和切换主题。例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* css variables */
.dark {
--bg: black;
--fg: white;
}
.white {
--bg: white;
--fg: black;
}
body {
/* use the variable */
background-color: var(--bg);
color: var(--fg);
}
button {
/* use the variable */
background-color: var(--bg);
color: var(--fg);
border-radius: 5px;
border-style: dashed;
}
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad at ipsum placeat maiores, fugiat neque sit, et
consequatur, fuga libero magni porro saepe distinctio quibusdam sapiente praesentium earum assumenda id!</p>
<button id='switch' onclick="switchTheme()">switch theme</button>
<script>
// setting theme when contents are loaded
window.addEventListener('load', function () {
var theme = localStorage.getItem('theme');
// when first load, choose an initial theme
if (theme === null || theme === undefined) {
theme = 'light';
localStorage.setItem('theme', theme);
}
// set theme
var html = document.querySelector("html");
// apply the variable
html.classList.add(theme);
})
function switchTheme() {
var theme = localStorage.getItem('theme');
var html = document.querySelector('html');
// choose new theme
if (theme === 'dark') {
new_theme = 'light';
} else {
new_theme = 'dark';
}
// remove previous class
html.classList.remove(theme);
// add new class
html.classList.add(new_theme);
// store theme
localStorage.setItem('theme', new_theme);
}
</script>
</body>
</html>