前端实现主题定制功能
1.link标签动态引入
1.1 思路
其做法就是提前准备好几套CSS主题样式文件,在需要的时候,创建link标签动态加载到head标签中,或者是动态改变link标签的href属性。
界面如下:
网络请求如下:
1.2 代码实现
创建light-theme.css和dark-theme.css:
/* light-theme.css */
body {
background-color: #ffffff;
color: #333333;
}
button {
background-color: #3498db;
color: #ffffff;
}
/* dark-theme.css */
body {
background-color: #2c3e50;
color: #ecf0f1;
}
button {
background-color: #e74c3c;
color: #ffffff;
}
通过JavaScript动态加载不同的CSS文件:
function loadTheme(theme) {
const head = document.head;
let link = document.getElementById('theme-link');
if (link) {
link.href = theme;
} else {
link = document.createElement('link');
link.id = 'theme-link';
link.rel = 'stylesheet';
link.href = theme;
head.appendChild(link);
}
}
// 监听主题切换按钮
document.getElementById('theme-switch').addEventListener('click', () => {
const currentTheme = document.getElementById('theme-link').href.includes('light-theme.css') ? 'dark-theme.css' : 'light-theme.css';
loadTheme(currentTheme);
});
1.3 优缺点分析
- 优点:
- 实现简单:只需切换样式文件,不需要复杂的逻辑。
- 适应性广:适用于所有前端框架和纯HTML项目。
- 缺点:
- 性能开销:每次切换都需要重新加载CSS文件,可能导致页面闪烁。
- 维护成本:需要维护多套完整的CSS文件,代码重复度高。
2.使用CSS变量
关于css变量的知识可以看我写的博客:https://blog.csdn.net/fageaaa/article/details/146512864
2.1 代码实现
在CSS文件的:root选择器中定义全局变量,例如:
:root {
--primary-color: #3498db;
--background-color: #ffffff;
--text-color: #333333;
}
在CSS中使用这些变量:
body