跨页面背景色平滑过渡的非单页非jQuery优化方案咨询
实现方案
核心优化思路
把原方案依赖后端Session存储前页背景色的逻辑移到前端sessionStorage实现,完全去掉后端参与逻辑,整体实现更轻量,适配静态页/任意后端语言场景。
具体实现步骤
- 每个页面仅需在body标签上标记当前页的目标背景色,无需后端渲染内联样式:
<!-- 红色页配置 --> <body data-current-bg="#f00"> <!-- 绿色页对应修改为 <body data-current-bg="#0f0"> --> <!-- 橙色页对应修改为 <body data-current-bg="#f90"> -->
- 在页面
<head>中加入一段同步执行的内联JS,避免页面加载时背景闪烁:
// 优先读取前页背景色设置为初始背景,先于页面渲染执行 const prevBg = window.sessionStorage.getItem('prev_page_bg'); if (prevBg) document.documentElement.style.backgroundColor = prevBg;
- 全站引入一次通用过渡逻辑JS即可:
document.addEventListener('DOMContentLoaded', () => { const currentBg = document.body.dataset.currentBg; const root = document.documentElement; // 开启背景色过渡 root.style.transition = 'background-color 3s ease-out'; // 切换到当前页目标背景色 root.style.backgroundColor = currentBg; // 过渡完成后存储当前背景色供下一页使用 const handleTransitionEnd = (e) => { if (e.propertyName === 'background-color') { window.sessionStorage.setItem('prev_page_bg', currentBg); root.removeEventListener('transitionend', handleTransitionEnd); } }; root.addEventListener('transitionend', handleTransitionEnd); });
方案优势
- 无后端依赖,不需要维护Session存储逻辑,也不需要后端动态输出body样式,静态站点也可直接使用
- 逻辑复用度高,通用JS仅需编写一次,新增页面仅需修改body的
data-current-bg属性即可 sessionStorage为标签页级隔离,用户同时打开多个站点标签页时背景状态不会互相干扰,比全局Session实现更合理- 首屏同步设置初始背景,不会出现背景闪白的问题
内容的提问来源于stack exchange,提问作者Jan Mirus
相关产品推荐
相关产品推荐

