Хорошо, я сделал этот пример для вас. Начните с 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, url, описание, действие, данные, historyState, действие;
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 ;)
Надеюсь, этот пример поможет вам ;)
Чао
Уилк
P.S. Подробнее:
- Управление историей браузера
- Объект истории
- История с инструкциями
person
Wilk
schedule
13.05.2012