实现js页面跳转页面
使用 window.location.href
通过修改 window.location.href 实现跳转,浏览器会加载新页面并记录到历史记录中:
window.location.href = "https://example.com";
使用 window.location.replace
与 href 类似,但不会在历史记录中生成新条目,用户无法通过返回按钮回到原页面:
window.location.replace("https://example.com");
使用 window.open
在新窗口或标签页中打开页面,可通过参数控制打开方式:
window.open("https://example.com", "_blank");
使用 meta 标签自动跳转
通过 HTML 的 <meta> 标签实现自动跳转,适合纯前端场景:
<meta http-equiv="refresh" content="0;url=https://example.com">
使用表单提交跳转
动态创建表单并提交,适合需要传递数据的场景:
const form = document.createElement('form');
form.method = 'POST';
form.action = 'https://example.com';
document.body.appendChild(form);
form.submit();
使用导航 API(现代浏览器)
通过现代浏览器的 Navigation API 实现跳转:
navigation.navigate("https://example.com");
使用锚点跳转
在同一页面内跳转到指定锚点:
window.location.hash = "#section-id";
注意事项
- 跨域限制:某些跳转方式可能受同源策略限制。
- SEO 影响:部分跳转方式可能不被搜索引擎友好处理。
- 用户体验:避免频繁自动跳转,可能被浏览器拦截。
以上方法可根据具体需求选择,常规推荐使用 window.location.href 或 window.location.replace。







