js实现网页跳转
使用 window.location.href 实现跳转
通过修改 window.location.href 属性可以实现页面跳转。这是最常用的方法之一,会触发浏览器历史记录。
window.location.href = "https://example.com";
使用 window.location.replace 实现跳转
window.location.replace() 方法会替换当前页面,不会在浏览器历史记录中留下记录。
window.location.replace("https://example.com");
使用 window.open 实现跳转
window.open() 方法可以在新窗口或当前窗口打开页面,取决于参数设置。
// 当前窗口打开
window.open("https://example.com", "_self");
// 新窗口打开
window.open("https://example.com", "_blank");
使用 meta 标签实现自动跳转
在 HTML 中插入 meta 标签可以实现自动跳转,通常用于几秒后自动跳转的场景。
<meta http-equiv="refresh" content="5;url=https://example.com">
使用表单提交实现跳转
通过 JavaScript 动态创建并提交表单可以实现跳转,适用于需要传递参数的场景。
const form = document.createElement("form");
form.method = "GET";
form.action = "https://example.com";
document.body.appendChild(form);
form.submit();
使用 history.pushState 实现无刷新跳转
history.pushState() 方法可以修改 URL 而不刷新页面,适用于单页应用。
history.pushState({}, "", "https://example.com/new-page");
使用锚点实现页面内跳转
通过修改 window.location.hash 可以实现页面内的锚点跳转。
window.location.hash = "#section-id";
使用 navigator 对象实现跳转
navigator 对象提供了一些跳转方法,但兼容性较差,不推荐主流使用。
navigator.app.loadUrl("https://example.com");






