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', '_blank');
// 在当前窗口打开
window.open('https://example.com', '_self');
使用 meta 标签实现跳转
通过动态创建 meta 标签可以实现自动跳转,常用于需要延迟跳转的场景。

const meta = document.createElement('meta');
meta.httpEquiv = 'refresh';
meta.content = '5;url=https://example.com';
document.head.appendChild(meta);
使用表单提交实现跳转
通过动态创建表单并提交可以实现跳转,适用于需要传递参数的场景。
const form = document.createElement('form');
form.method = 'GET';
form.action = 'https://example.com';
document.body.appendChild(form);
form.submit();
使用 history.pushState 实现无刷新跳转
history.pushState 方法可以修改 URL 而不刷新页面,适用于单页应用(SPA)。
history.pushState({}, '', 'https://example.com');
使用 location.assign 实现跳转
location.assign 方法会加载新页面并保留浏览历史,与 location.href 类似。

window.location.assign('https://example.com');
使用 iframe 实现跳转
通过动态创建 iframe 并设置其 src 属性可以实现跳转,适用于需要在特定区域加载页面的场景。
const iframe = document.createElement('iframe');
iframe.src = 'https://example.com';
document.body.appendChild(iframe);
使用响应式跳转
根据设备类型或浏览器特性实现条件跳转,例如移动端跳转到移动版页面。
if (/Mobi|Android/i.test(navigator.userAgent)) {
window.location.href = 'https://m.example.com';
}
使用事件触发跳转
通过事件监听实现跳转,例如点击按钮后跳转。
document.getElementById('button').addEventListener('click', () => {
window.location.href = 'https://example.com';
});






