html5 history api
有时候开发者会操作浏览器的history记录来规范用户的操作行为。
开发者通常是通过在历史记录的list中进行筛选,来控制页面的跳转,但是对于动态的链接实现起来十分不便。
html5提供了history的接口后,对开发者而言操作更加方便高效。
api方法
1 history.length 检查历史堆栈数量
console.log(history.length);
2 跳转向前/向后操作
console.log(history.forward());
console.log(history.back());
3 跳转到指定的堆栈位置
console.log(history.go(-3));
动态网页是指当浏览器改变页面的内容的时候,url地址栏不改变。通常我们使用片段标示符来监控页面是否变化,通常我们定义一个页面的id属性,提供一些该页面独有的状态信息,但是这完全依赖于后端服务的支持。
hashbangs技术:f#!king 这个技术 通过JavaScript识别一组标识符,来决定哪个页面和状态应显示,并且更新地址栏。
例子 http://twitter.com/#!/akamike 转变成 http://twitter.com/akamike
缺点:1 只能在客户端访问,只能通过javascript来操作。2 会破坏链接的标准形式,不规范。 3 使链接看起来像是一个浏览器hack行为。
使用histroy接口
1 history.pushState(data,title,url)
data:设置标签要显示的内容 tilte:设置标签的名字 url:显示到地址栏的链接
function clickHandler(event) {
// Add an item to the history log
history.pushState(data, event.target.textContent,event.target.href);
return event.preventDefault();
}
2 导航的histroy事件
// Revert to a previously saved state
window.addEventListener('popstate', function(event) {
console.log('popstate fired!');
updateContent(event.state);
});
3 替换已有的histroy链接
// Store the initial content so we can revisit it later
history.replaceState({
content: contentEl.textContent,
photo: photoEl.src
}, document.title, document.location.href);
支持的浏览器: Chrome (5+), Safari (5.0+), Firefox (4.0+), and Opera (11.50+) have support for the new History API. like Mobile Safari on iOS 4+. Unfortunately, IE 9 and below lack support, but it when it arrives.
出处 http://html5doctor.com/history-api/
demo http://html5doctor.com/demos/history/bob

浙公网安备 33010602011771号