h5实现页面切换
实现页面切换的常见方法
使用 <a> 标签跳转
通过超链接实现页面切换,适合传统多页面应用(MPA)。
<a href="page2.html">跳转到页面2</a>
使用 window.location
通过 JavaScript 动态跳转页面,可结合条件逻辑。
window.location.href = "page2.html";
使用 history.pushState 实现无刷新切换
适用于单页面应用(SPA),配合路由库(如 Vue Router、React Router)。
history.pushState({}, "", "page2.html");
// 需监听 popstate 事件处理后退操作
window.addEventListener("popstate", () => {
// 更新页面内容
});
单页面应用(SPA)实现方案
基于 Vue Router
安装 Vue Router 后配置路由:
const routes = [
{ path: '/page1', component: Page1 },
{ path: '/page2', component: Page2 }
];
const router = new VueRouter({ routes });
new Vue({ router }).$mount('#app');
通过 <router-link> 切换:

<router-link to="/page1">页面1</router-link>
<router-link to="/page2">页面2</router-link>
基于 React Router
配置路由并切换页面:
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
function App() {
return (
<Router>
<Link to="/page1">页面1</Link>
<Link to="/page2">页面2</Link>
<Route path="/page1" component={Page1} />
<Route path="/page2" component={Page2} />
</Router>
);
}
动态加载内容切换
通过 AJAX/Fetch 加载内容
无需跳转页面,动态更新部分内容:
fetch('content.html')
.then(response => response.text())
.then(html => {
document.getElementById('container').innerHTML = html;
});
使用 CSS 隐藏/显示内容
通过切换 CSS 类实现伪页面切换:

<div class="page active" id="page1">内容1</div>
<div class="page" id="page2">内容2</div>
<style>
.page { display: none; }
.page.active { display: block; }
</style>
<script>
function showPage(pageId) {
document.querySelectorAll('.page').forEach(el => {
el.classList.remove('active');
});
document.getElementById(pageId).classList.add('active');
}
</script>
注意事项
-
SPA 需配置服务器
确保服务器返回index.html处理所有路由请求,避免 404 错误。 -
SEO 优化
动态加载内容需考虑预渲染或服务端渲染(SSR)方案。 -
状态管理
页面切换时注意保存状态,可使用 Vuex、Redux 或本地存储。





