当前位置:首页 > JavaScript

js实现跳转

2026-01-08 12:15:48JavaScript

使用 window.location 跳转

通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。

// 方法1:直接赋值
window.location.href = 'https://example.com';

// 方法2:简写形式
window.location = 'https://example.com';

// 带参数的跳转
window.location.href = 'https://example.com?param=value';

使用 location.assign()

location.assign() 方法会加载新文档并保留浏览器历史记录,允许用户通过后退按钮返回原页面。

location.assign('https://example.com');

使用 location.replace()

location.replace() 直接替换当前页面,不保留历史记录,用户无法通过后退按钮返回。

js实现跳转

location.replace('https://example.com');

使用 window.open()

在新标签页或窗口中打开链接,可通过参数控制打开方式。

// 新标签页打开(默认)
window.open('https://example.com');

// 新窗口打开
window.open('https://example.com', '_blank');

// 当前窗口打开(等效于 location.href)
window.open('https://example.com', '_self');

使用 meta 标签跳转

通过动态插入 <meta> 标签实现延迟跳转,常用于页面自动跳转场景。

js实现跳转

// 3秒后跳转
const meta = document.createElement('meta');
meta.httpEquiv = 'refresh';
meta.content = '3;url=https://example.com';
document.head.appendChild(meta);

使用表单提交跳转

通过动态创建表单并提交实现 POST 跳转,适用于需要传递表单数据的场景。

const form = document.createElement('form');
form.method = 'POST';
form.action = 'https://example.com';

const input = document.createElement('input');
input.type = 'hidden';
input.name = 'data';
input.value = 'example';
form.appendChild(input);

document.body.appendChild(form);
form.submit();

使用 History API

通过 history.pushState()history.replaceState() 修改浏览器地址栏而不刷新页面,适用于单页应用(SPA)。

// 添加历史记录并跳转
history.pushState({}, '', '/new-path');

// 替换当前历史记录
history.replaceState({}, '', '/new-path');

注意事项

  • 使用 window.open() 可能被浏览器拦截,需确保由用户触发(如点击事件)。
  • location.replace() 不保留历史记录,适合登录后跳转等场景。
  • History API 需配合前端路由框架使用,单独调用可能需手动处理页面内容更新。

标签: 跳转js
分享给朋友:

相关文章

vue实现js休眠

vue实现js休眠

Vue 中实现 JavaScript 休眠 在 Vue 中实现 JavaScript 休眠通常需要使用异步方式,以避免阻塞主线程。以下是几种常见方法: 使用 setTimeout 和 Pro…

vue实现页面跳转

vue实现页面跳转

vue实现页面跳转的方法 在Vue中实现页面跳转主要有以下几种方式: 使用router-link组件 router-link是Vue Router提供的组件,用于声明式导航: <router…

vue文件实现页面跳转

vue文件实现页面跳转

使用 router-link 实现跳转 在 Vue 模板中直接使用 <router-link> 组件,通过 to 属性指定目标路径: <router-link to="/tar…

js实现选项卡

js实现选项卡

实现选项卡的基本思路 选项卡通常由一组标签和对应的内容面板组成。点击标签时,显示对应的内容面板,隐藏其他面板。实现这一效果需要结合HTML结构、CSS样式和JavaScript交互逻辑。 HTML结…

h5实现登录页面跳转页面跳转页面跳转页面

h5实现登录页面跳转页面跳转页面跳转页面

实现登录页面跳转的方法 在H5中实现登录页面跳转可以通过多种方式完成,以下是一些常见的方法: 使用JavaScript的window.location方法 通过JavaScript的window.l…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…