HTML中如何基于指定main目录设置可移植的通用跳转路径
解决方案
方案1:纯HTML相对路径实现(优先推荐)
只要保证main目录内部的文件夹结构固定,不需要依赖站点根目录配置,直接用相对于当前HTML文件的相对路径即可:
- 部署在
main/component1/index.html的文件,跳转路径写../component2/,../表示返回上一级目录(即main目录),再进入component2目录 - 部署在
main/component3/dir1/index.html的文件,跳转路径写../../component2/,两层../依次返回至component3、main目录,再进入component2目录
示例代码:
<!-- main/component1/index.html 按钮写法 --> <a href="../component2/"><button>跳转到component2</button></a> <!-- main/component3/dir1/index.html 按钮写法 --> <a href="../../component2/"><button>跳转到component2</button></a>
该方案完全由原生HTML实现,无需引入额外脚本,只要main目录内部结构不改动,不管你将main目录解压部署到站点的任意路径下,跳转链接都可以正常生效。
方案2:JS动态匹配路径(适用于多位置复用同一份HTML文件的场景)
如果你需要两份index.html是完全相同的复用文件,不想单独配置不同的相对路径,可以通过JS动态识别main目录位置:
- 先在
main根目录下新增一个唯一标识文件,比如空的main_root_flag.txt,用来定位main目录的层级 - 所有
index.html共用如下代码即可:
<button id="jumpToComponent2">跳转到component2</button> <script> async function findMainRoot() { const pathArr = window.location.pathname.split('/').filter(i => i); // 从当前目录逐层向上查找标识文件,确认main根目录位置 while (pathArr.length) { const testPath = '/' + pathArr.join('/') + '/main_root_flag.txt'; try { const res = await fetch(testPath, { method: 'HEAD' }); if (res.ok) return '/' + pathArr.join('/') + '/'; } catch(err) {} pathArr.pop(); } // 兜底逻辑可自定义 return './'; } document.getElementById('jumpToComponent2').addEventListener('click', async () => { const mainRoot = await findMainRoot(); window.location.href = mainRoot + 'component2/'; }); </script>
该方案不管HTML文件放在main目录下的任意层级,都可以自动匹配main根目录位置,不受站点根目录变动影响。
内容的提问来源于stack exchange,提问作者Joshua von Damm
相关产品推荐
相关产品推荐

