iframe 子页面主题同步实现方案
1. 目标
让所有通过 iframe 加载的子页面自动继承主框架的主题色系,子页面加载时主动从 localStorage 读取主题并应用。
2. 当前架构分析
主框架 (index.html)
- 主题配置存储在
localStorage['lay_menu_theme']和后端/user/theme/save config.js中的selectThemes(i)方法通过动态注入<style id="lay-theme-style">实现主题切换main.js中的themeCallback负责主题切换后的持久化存储
子页面 (如 articles.html, home.html 等)
- 独立加载
layui.css和各自样式 - 当前不包含主题同步逻辑
3. 实现方案
步骤 1:创建公共主题同步脚本
文件: static/js/theme-sync.js
功能:
1. 页面加载时从 localStorage 读取 lay_menu_theme
2. 解析主题配置,动态注入主题样式到子页面
3. 提供 CSS 变量注入方式,覆盖 layui 默认样式
步骤 2:在 main.js 中增强主题同步
修改 main.js 的 themeCallback:
- 主题切换时,将生成的 CSS 规则存储到 localStorage['lay_theme_css']
- 子页面可直接读取应用
步骤 3:子页面引入主题同步脚本
在所有子页面的 <head> 中添加:
<script src="{{ url_for('static', filename='js/theme-sync.js') }}"></script>
4. 技术细节
theme-sync.js 核心逻辑
(function() {
var themeConfig = localStorage.getItem('lay_menu_theme');
if (!themeConfig) return;
var theme = JSON.parse(themeConfig);
var themeIndex = theme.theme || 0;
// 主题颜色数组(与 config.js themeObj 保持一致)
var colors = {
arr1: ['131519','03152A','2a1103','335eea',...],
arr2: ['ffffff','ffffff','ffffff','ffffff',...],
arr3: ['131519','03152A','2a1103','335eea',...],
selectBg: ['13b980','3b91ff','dd540a','335eea',...],
selectColor: ['ffffff','ffffff','ffffff','ffffff',...]
};
// 生成并注入 CSS
var css = generateChildThemeCSS(themeIndex, colors);
var style = document.createElement('style');
style.id = 'child-theme-style';
style.textContent = css;
document.head.appendChild(style);
})();
子页面关键 CSS 覆盖规则
/* 按钮主题色 */
.layui-btn { background-color: #{头部背景色} !important; }
.layui-btn-primary { background-color: #fcfcfc !important; }
/* 表单元素 */
.layui-form-label { color: #{头部文字色}; }
.layui-input:focus, .layui-textarea:focus {
border-color: #{选中色} !important;
}
/* 表格 */
.layui-table th { background-color: #{选中色}24; }
/* 标签页 */
.layui-tab-brief > .layui-tab-title .layui-this {
color: #{选中色} !important;
}
5. 涉及文件
| 文件 | 修改内容 |
|---|---|
static/js/theme-sync.js |
新建 - 子页面主题同步脚本 |
static/js/main.js |
修改 - 主题切换时存储 CSS 到 localStorage |
templates/page/articles.html |
添加主题同步脚本引用 |
templates/page/home.html |
添加主题同步脚本引用 |
templates/page/set.html |
添加主题同步脚本引用 |
templates/page/*.html |
其他需要主题同步的子页面 |
6. 实现顺序
- 创建 theme-sync.js - 子页面主题同步核心脚本
- 修改 main.js - 在 themeCallback 中存储主题 CSS
- 修改子页面模板 - 添加脚本引用
- 测试验证 - 切换主题后检查子页面是否同步
7. 注意事项
- 不修改 config.js,保持原有逻辑
- 子页面需要加载
layui.css才能使用 Layui 组件 - 主题颜色数组需与
config.js的themeObj保持完全一致 - CSS 优先级使用
!important确保覆盖
评论
评论列表