当前位置:首页 > JavaScript

js 实现跳转

2026-01-15 14:58:56JavaScript

使用 window.location.href 进行跳转

通过修改 window.location.href 可以跳转到指定 URL,浏览器会加载新页面:

window.location.href = 'https://example.com';

使用 window.location.replace 替换当前页面

replace 方法会替换当前页面,且不会在浏览器历史记录中留下原页面的记录:

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

使用 window.open 在新窗口或标签页打开

通过 window.open 可以在新窗口或标签页中打开链接,支持指定窗口特性:

window.open('https://example.com', '_blank');

使用 location.assign 加载新页面

assign 方法会加载新页面,并在浏览器历史记录中保留原页面:

js 实现跳转

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

使用锚点 (hash) 进行页面内跳转

通过修改 location.hash 可以实现页面内的锚点跳转:

window.location.hash = '#section-id';

使用 history.pushStatereplaceState 无刷新跳转

适用于单页应用 (SPA),通过 pushStatereplaceState 修改 URL 而不刷新页面:

history.pushState({}, '', '/new-path');

js 实现跳转

history.replaceState({}, '', '/new-path');

使用 <a> 标签模拟点击跳转

通过 JavaScript 创建或触发 <a> 标签的点击事件实现跳转:

const link = document.createElement('a');
link.href = 'https://example.com';
link.click();

使用 meta 标签自动跳转

通过动态插入 <meta> 标签实现自动跳转:

const meta = document.createElement('meta');
meta.httpEquiv = 'refresh';
meta.content = '0;url=https://example.com';
document.head.appendChild(meta);

使用表单提交跳转

通过动态创建表单并提交实现跳转:

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

注意事项

  • 使用 window.open 可能会被浏览器弹窗拦截器阻止。
  • replaceassign 的区别在于是否保留历史记录。
  • pushStatereplaceState 需配合前端路由框架使用。
  • 锚点跳转仅适用于页面内已有对应 id 的元素。

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

相关文章

vue实现界面跳转

vue实现界面跳转

路由配置 在Vue项目中实现界面跳转通常依赖Vue Router。需在router/index.js中配置路由路径和组件映射关系: import { createRouter, createWeb…

vue实现前端跳转

vue实现前端跳转

Vue 实现前端跳转的方法 在 Vue 中实现前端跳转通常使用 Vue Router,以下是几种常见的跳转方式: 声明式导航(模板中使用 <router-link>) 在模板中直接使用…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableEleme…

jquery.js

jquery.js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,用于简化 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它的设计宗旨是“Write Less, Do Mor…

vue 实现登录跳转

vue 实现登录跳转

实现登录跳转的核心逻辑 在Vue中实现登录跳转通常涉及路由守卫、状态管理和API交互。以下是具体实现方式: 配置路由守卫 在路由配置文件中添加beforeEach守卫,检查用户是否已登录。未登录…

vue实现js休眠

vue实现js休眠

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