前端页面跳转的6大类方法及其使用场景特性分析
1. a标签跳转
-
代码示例:
-
在当前页面打开:
HTML复制
<a href="https://www.baidu.com">跳转</a> -
在新窗口打开:
HTML复制
<a href="https://www.baidu.com" target="_blank">跳转</a>
-
-
适用场景:
- 适用于页面中跳转到固定的地址。
2. JS中模拟a标签跳转
-
代码示例:
JavaScript复制
function imitateClick(url) { let aEle = document.createElement("a"); aEle.setAttribute("href", url); aEle.setAttribute("target", "_blank"); aEle.setAttribute("id", "previewJumpEle"); // 防止重复添加 if (!document.getElementById("previewJumpEle")) { document.body.appendChild(aEle); } // 模拟点击 aEle.click(); (aEle.remove && aEle.remove()) || (aEle.removeNode && aEle.removeNode(true)); } imitateClick('https://www.baidu.com'); -
适用场景:
- 适用于在JS中直接做无感跳转。
- 注意:某些浏览器可能会拦截此操作,需谨慎使用。
3. JS中window对象location属性跳转
-
代码示例:
-
覆盖当前页面跳转:
JavaScript复制
window.location.href = 'https://www.baidu.com'; -
覆盖顶层地址跳转:
JavaScript复制
top.window.location.href = 'https://www.baidu.com';
-
-
适用场景:
window.location.href:在iframe嵌套内页跳转时,只能改变iframe的src。top.window.location.href:在iframe嵌套内页跳转时,可以覆盖顶层地址打开新页面,且浏览器无拦截。
4. JS中window对象的open方法跳转
-
代码示例:
-
新窗口打开一个链接:
JavaScript复制
window.open('https://www.baidu.com'); -
打开一个新的空白窗口(类似弹窗):
JavaScript复制
window.open('https://m.book118.com','','left=200,top=200,width=200,height=100');
-
-
适用场景:
window.open和top.window.open效果相同,都是新窗口打开页面。- 可以指定窗口特征,用作弹窗。
- 在iframe中使用时可能会被浏览器拦截。
5. 重定向跳转
-
代码示例:
-
当前页面地址重定向:
JavaScript复制
window.location.replace('https://www.baidu.com'); -
顶层地址重定向:
JavaScript复制
top.window.location.replace('https://www.baidu.com');
-
-
适用场景:
window.location.replace():在iframe中使用时,只会重定向src地址。top.window.location.replace():效果与top.window.location.href相同,可以在iframe中使用,且浏览器无拦截。
6. meta标签跳转
-
代码示例:
HTML复制
<meta http-equiv="refresh" content="5;url=http://www.w3school.com.cn">content="5;url=http://www.w3school.com.cn":5秒后跳转到指定地址。
-
适用场景:
- 适用于进入页面后直接跳转。
总结
- a标签跳转:适用于固定地址的跳转。
- JS模拟a标签跳转:适用于无感跳转,但需注意浏览器拦截。
- window.location.href:适用于覆盖当前页面或iframe的跳转。
- window.open:适用于新窗口跳转,可指定窗口特征,但iframe中可能被拦截。
- window.location.replace:适用于重定向跳转,iframe中使用时需注意。
- meta标签跳转:适用于页面加载后自动跳转。