当前位置:首页 > 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 中实现页面跳转主要通过路由(Vue Router)完成,以下是几种常见的方式: 声明式导航(模板中使用 <router-link>) 在模板中直…

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.…

js实现页面跳转

js实现页面跳转

使用 window.location.href 通过修改 window.location.href 属性实现页面跳转: window.location.href = 'https://example…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js实现图片轮播

js实现图片轮播

实现基础图片轮播 使用HTML、CSS和JavaScript创建一个简单的图片轮播。HTML部分定义轮播容器和图片,CSS设置样式和动画效果,JavaScript处理轮播逻辑。 <div cl…

js实现验证

js实现验证

验证表单输入 使用JavaScript验证表单输入是常见的需求。可以通过监听表单提交事件,检查输入字段是否符合要求。 document.getElementById('myForm').addEv…