当前位置:首页 > 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 实现页面跳转

vue 实现页面跳转

vue 实现页面跳转的方法 在 Vue 中实现页面跳转主要通过路由(Vue Router)完成,以下是几种常见的方式: 声明式导航(模板中使用 <router-link>) 在模板中直接…

jquery跳转

jquery跳转

jQuery 页面跳转方法 使用 jQuery 实现页面跳转有多种方式,以下是几种常见的方法: 使用 window.location.href $(document).ready(function…

js实现交换

js实现交换

交换变量的方法 在JavaScript中,交换两个变量的值有多种方法。以下是常见的几种实现方式: 使用临时变量 通过引入一个临时变量来存储其中一个变量的值,实现交换: let a = 1; le…

vue 实现页面跳转

vue 实现页面跳转

Vue 实现页面跳转的方法 在 Vue 中实现页面跳转可以通过多种方式,主要包括使用 Vue Router 提供的导航方法和原生 JavaScript 的方式。 使用 Vue Router 的 ro…

vue实现导航跳转

vue实现导航跳转

vue-router 基本跳转方法 在 Vue 项目中实现导航跳转主要通过 vue-router 完成。安装路由依赖: npm install vue-router 在 router/index.j…

js实现文字滚动

js实现文字滚动

实现文字滚动的几种方法 使用CSS动画实现滚动 通过CSS的@keyframes和transform属性可以实现平滑的文字滚动效果。 <style> .scroll-text { w…