Swup JS页面切换时添加/移除区块的实现方案咨询
解决SwupJS页面切换时页脚动态显示/隐藏的方案
核心思路是利用Swup的页面切换事件钩子,根据跳转的来源页面和目标页面路径,动态控制页脚的显示状态或DOM操作,无需移除Swup容器即可保留全站过渡效果。
具体实现步骤
1. 监听Swup页面切换事件
使用Swup提供的swup:willReplaceContent(内容替换前触发)或swup:contentReplaced(内容替换后触发)事件,在页面切换时执行逻辑判断。推荐用swup:willReplaceContent,能配合过渡动画实现更自然的效果。
2. 编写逻辑控制页脚
假设页脚DOM元素为<footer id="site-footer">...</footer>,示例代码如下:
// 获取页脚元素 const siteFooter = document.getElementById('site-footer'); // 页面初始加载时判断是否需要隐藏页脚 document.addEventListener('DOMContentLoaded', () => { const currentPath = window.location.pathname; // 匹配所有无页脚页面,比如404、自定义无页脚路径 const noFooterPages = ['/404', '/custom-no-footer']; if (noFooterPages.includes(currentPath)) { siteFooter.classList.add('footer-hidden'); } }); // 监听Swup页面切换事件 swup.on('swup:willReplaceContent', () => { const targetPath = swup.transition.to.url.pathname; const fromPath = swup.transition.from.url.pathname; const noFooterPages = ['/404', '/custom-no-footer']; // 跳转到无页脚页面:隐藏页脚 if (noFooterPages.includes(targetPath)) { siteFooter.classList.add('footer-hidden'); } // 从无页脚页面跳回有页脚页面:显示页脚 if (noFooterPages.includes(fromPath) && !noFooterPages.includes(targetPath)) { siteFooter.classList.remove('footer-hidden'); } });
3. 添加过渡样式(可选)
为了让页脚的显示/隐藏更平滑,配合Swup的页面过渡动画,添加CSS样式:
#site-footer { transition: all 0.3s ease; opacity: 1; visibility: visible; height: auto; } .footer-hidden { opacity: 0; visibility: hidden; height: 0; overflow: hidden; }
扩展说明
- 如果无页脚页面路径较多,可以用正则表达式匹配,比如
/^\/(404|page-.*-no-footer)$/来匹配符合规则的路径。 - 若需要完全移除/插入页脚(而非隐藏),可以提前保存页脚的HTML内容,切换时动态操作DOM:
// 初始保存页脚内容 window.footerHtml = siteFooter.innerHTML; // 跳转到无页脚页面时移除 siteFooter.remove(); // 跳回时重新插入 siteFooter.innerHTML = window.footerHtml; document.body.appendChild(siteFooter);
内容的提问来源于stack exchange,提问作者IIIu6ko
相关产品推荐
相关产品推荐

