1 回答
TA贡献1780条经验 获得超5个赞
您可以随意命名本地存储键,但请记住对值进行相应的操作。
<button onclick="toggleMode()">Toggle theme</button>
<script>
// Theme mode key name
const LS_THEME_KEY = "theme_mode";
// Possible theme mode local storage values
const THEME_MODE_LIGHT = 0;
const THEME_MODE_DARK = 1;
// Class to be applied when dark mode is active
const BODY_DARK_MODE_CLASS = "dark-mode";
// Default theme
const DEFAULT_THEME_MODE = THEME_MODE_DARK;
// Look up current theme mode and modify the body
// tag class list accordingly.
const syncBodyClassList = (setValue) => {
const currThemeMode = setValue !== undefined ? setValue : parseInt(localStorage.getItem(LS_THEME_KEY) || DEFAULT_THEME_MODE);
if (currThemeMode === THEME_MODE_DARK) {
// turn the dark theme on
document.body.classList.add(BODY_DARK_MODE_CLASS);
} else {
// turn the dark theme off
document.body.classList.remove(BODY_DARK_MODE_CLASS);
}
};
const setThemeMode = (mode) => {
localStorage.setItem(LS_THEME_KEY, mode);
syncBodyClassList(mode);
}
// Toggle current theme and save it into the local storage
function toggleMode() {
const currentValue = parseInt(localStorage.getItem(LS_THEME_KEY) || DEFAULT_THEME_MODE);
if (currentValue === THEME_MODE_DARK) {
setThemeMode(THEME_MODE_LIGHT);
} else {
setThemeMode(THEME_MODE_DARK);
}
}
const initPage = () => {
syncBodyClassList();
}
initPage();
</script>
添加回答
举报