{{ Title }}
在写MioMoeV2的时候想实现一个点击按钮黑白主题切换的功能,直接上代码:
我已经在body标签引入了
mdui-theme-layout-auto
的class类名
新建一个按钮,id为
toggleTheme
以下是MioMoe主题的JavaScript代码:
// 主题样式
// 切换主题并保存
document.getElementById('toggleTheme').addEventListener('click', function() {
var body = document.body;
var currentTheme = body.classList.contains('mdui-theme-layout-light') ? 'mdui-theme-layout-light' :
body.classList.contains('mdui-theme-layout-dark') ? 'mdui-theme-layout-dark' :
'mdui-theme-layout-auto';
// 根据当前主题切换到下一个主题
switch (currentTheme) {
case 'mdui-theme-layout-auto':
body.classList.remove('mdui-theme-layout-auto');
body.classList.add('mdui-theme-layout-light');
localStorage.setItem('theme', 'mdui-theme-layout-light');
mdui.snackbar({
message: '当前为:浅色模式',
position: 'right-bottom',
});
break;
case 'mdui-theme-layout-light':
body.classList.remove('mdui-theme-layout-light');
body.classList.add('mdui-theme-layout-dark');
localStorage.setItem('theme', 'mdui-theme-layout-dark');
mdui.snackbar({
message: '当前为:深色模式',
position: 'right-bottom',
});
break;
case 'mdui-theme-layout-dark':
body.classList.remove('mdui-theme-layout-dark');
body.classList.add('mdui-theme-layout-auto');
localStorage.setItem('theme', 'mdui-theme-layout-auto');
mdui.snackbar({
message: '当前为:自动模式',
position: 'right-bottom',
});
break;
}
});
// 加载主题设置
document.addEventListener('DOMContentLoaded', function() {
var body = document.body;
var savedTheme = localStorage.getItem('theme');
if (savedTheme) {
// 移除所有可能的主题类
body.classList.remove('mdui-theme-layout-auto', 'mdui-theme-layout-light', 'mdui-theme-layout-dark');
// 添加保存的主题类
body.classList.add(savedTheme);
}
});