js实现页面切换
使用 window.location 实现页面跳转
通过修改 window.location.href 可以直接跳转到新页面:
window.location.href = "https://example.com"; // 跳转到指定URL
window.location.replace("https://example.com"); // 替换当前页面(不保留历史记录)
使用 history.pushState 实现无刷新路由
适合单页应用(SPA),动态修改URL而不刷新页面:
history.pushState({}, "", "/new-page"); // 添加新历史记录
history.replaceState({}, "", "/updated-page"); // 替换当前历史记录
需配合 popstate 事件监听URL变化:

window.addEventListener("popstate", () => {
console.log("URL changed:", window.location.pathname);
});
使用 <a> 标签模拟跳转
通过编程方式触发标签点击:
const link = document.createElement("a");
link.href = "/target-page";
link.click(); // 模拟用户点击
使用框架路由(React/Vue示例)
React Router 示例:

import { useNavigate } from "react-router-dom";
function Component() {
const navigate = useNavigate();
navigate("/target-page"); // 编程式导航
}
Vue Router 示例:
this.$router.push("/target-page"); // 跳转并保留历史
this.$router.replace("/no-history"); // 替换当前路由
使用 iframe 切换局部内容
动态修改 iframe 的 src 属性实现局部加载:
<iframe id="content-frame"></iframe>
<script>
document.getElementById("content-frame").src = "/partial-page.html";
</script>
注意事项
- 普通跳转会触发页面刷新,单页应用推荐使用路由库(如 React Router/Vue Router)。
history.pushState需自行处理路由逻辑,通常与框架集成使用。- 跨域页面无法通过
window.location获取目标页面内容。






