好的,我为你做了这个例子。
从 HTML 代码开始(index.html):
<!DOCTYPE html>
<html>
<head>
<title>Stackoverflow</title>
<script type="text/javascript" src="sof.js"> </script>
</head>
<body onLoad="load();">
<ul id="menu">
<li><a href="/home">home</a></li>
<li><a href="/about">about</a></li>
<li><a href="/blog">blog</a></li>
<li><a href="/photos">photos</a></li>
</ul>
<button onclick="back ();">Back</button>
<button onclick="ff ();">Forward</button>
<div>
Action: <span id="action"></span><br/>
Url: <span id="url"></span><br/>
Description: <span id="description"></span>
</div>
</body>
</html>
然后是javascript文件(sof.js):
var menu, url, description, action, data, historyState, act;
function $ (id) {return document.getElementById (id);}
// Updates infos
function update (state) {
action.innerHTML = act;
url.innerHTML = state.url;
description.innerHTML = state.description;
}
// Goes back
function back () {
act = 'Back';
history.back ();
}
// Goes forward
function ff () {
act = 'Forward';
history.forward ();
}
function load () {
menu = $ ('menu');
url = $ ('url');
description = $ ('description');
action = $ ('action');
// State to save
historyState = {
home: {
description: 'Homepage'
} ,
about: {
description: 'Infos about this website'
} ,
blog: {
description: 'My personal blog'
} ,
photos: {
description: 'View my photos'
}
};
// This is fired when history.back or history.forward is called
window.addEventListener ('popstate', function (event) {
var hs = history.state;
if ((hs === null) || (hs === undefined)) hs = event.state;
if ((hs === null) || (hs === undefined)) hs = window.event.state;
if (hs !== null) update (hs);
});
menu.addEventListener ('click', function (event) {
var el = event.target;
// Prevents url reload
event.preventDefault ();
// Handles anchors only
if (el.nodeName === 'A') {
// Gets url of the page
historyState[el.innerHTML].url = el.getAttribute ('href');
// Creates a new history instance and it saves state on it
history.pushState (historyState[el.innerHTML], null, el.href);
act = 'Normal navigation';
update (historyState[el.innerHTML]);
}
});
// Handles first visit navigation
var index = location.pathname.split ('/');
index = index[index.length-1];
if (index !== '') {
historyState[index].url = location.pathname;
history.pushState (historyState[index], null, location.pathname);
act = 'First visit';
update (historyState[index]);
}
}
还有一个 .htaccess 用于直接请求:
RewriteEngine On
RewriteRule ^home$ ./index.html
RewriteRule ^about$ ./index.html
RewriteRule ^blog$ ./index.html
RewriteRule ^photos$ ./index.htm
每次单击锚点时,都会将一个新的历史实例推送到历史堆栈中,并与它一起保存一个对象(称为状态):本地 url 更改但加载被“event.preventDefault()”停止方法。
此外,更新了一些信息(如 URL、描述和操作)。
然后,使用“后退”和“前进”按钮,您可以浏览历史并使用“history.state”(或 event.state 或 window.event.state,取决于浏览器)检索当前状态.
最后,如果你直接在地址栏中输入整个 url,它的工作原理与上面的 .htaccess 相同;)
我希望这个例子对你有帮助;)
调
威尔
PS:更多详情:
- Manipulating the browser history
- History object
- History howto