73 lines
2.6 KiB
HTML
73 lines
2.6 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="zh-CN">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>修改URL不刷新页面</title>
|
||
<style>
|
||
.btn-group { margin: 20px; }
|
||
button { padding: 8px 16px; margin-right: 10px; cursor: pointer; }
|
||
.content { margin: 20px; padding: 20px; border: 1px solid #ccc; }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<div class="btn-group">
|
||
<button id="btn1">修改URL(新增记录)</button>
|
||
<button id="btn2">替换URL(无新增记录)</button>
|
||
<button id="btn3">模拟路由回退</button>
|
||
</div>
|
||
<div class="content">
|
||
当前URL:<span id="currentUrl"></span>
|
||
<br>
|
||
页面内容:<span id="pageContent">初始内容</span>
|
||
</div>
|
||
|
||
<script>
|
||
// 初始化显示当前URL
|
||
const currentUrlEl = document.getElementById('currentUrl');
|
||
const pageContentEl = document.getElementById('pageContent');
|
||
updateUrlDisplay();
|
||
|
||
// 1. 使用pushState修改URL(新增历史记录)
|
||
document.getElementById('btn1').addEventListener('click', () => {
|
||
// 参数说明:
|
||
// 第1个参数:状态对象(可存任意数据,后退时可获取)
|
||
// 第2个参数:页面标题(多数浏览器忽略,传空即可)
|
||
// 第3个参数:新的URL(可以是相对路径或绝对路径)
|
||
history.pushState({ page: 'page1' }, '', '/page1?name=test');
|
||
updateUrlDisplay();
|
||
// 可根据URL修改页面内容(模拟路由切换)
|
||
pageContentEl.textContent = '这是page1的内容(未刷新页面)';
|
||
});
|
||
|
||
// 2. 使用replaceState修改URL(替换当前记录)
|
||
document.getElementById('btn2').addEventListener('click', () => {
|
||
history.replaceState({ page: 'page2' }, '', '/page2?id=123');
|
||
updateUrlDisplay();
|
||
pageContentEl.textContent = '这是page2的内容(未刷新页面)';
|
||
});
|
||
|
||
// 3. 模拟回退
|
||
document.getElementById('btn3').addEventListener('click', () => {
|
||
history.back();
|
||
});
|
||
|
||
// 监听浏览器前进/后退事件(popstate)
|
||
window.addEventListener('popstate', (e) => {
|
||
updateUrlDisplay();
|
||
// 可根据历史状态对象更新页面内容
|
||
if (e.state && e.state.page === 'page1') {
|
||
pageContentEl.textContent = '回退到page1的内容';
|
||
} else if (e.state && e.state.page === 'page2') {
|
||
pageContentEl.textContent = '回退到page2的内容';
|
||
} else {
|
||
pageContentEl.textContent = '初始内容';
|
||
}
|
||
});
|
||
|
||
// 更新URL显示
|
||
function updateUrlDisplay() {
|
||
currentUrlEl.textContent = window.location.href;
|
||
}
|
||
</script>
|
||
</body>
|
||
</html> |