需求
列表页是ajax动态加载的,每次点击进入查看后返回,会丢失之前的位置,并且列表需要重新加载一次。
思路
绑定点击事件,点击的时候获取当前位置和列表HTML,存入sessionStorage。
后退的时候要判断是否从前一个页面返回的,这里就用到 **history.replaceState**
代码
$('#list a').live('click',function(e){
history.replaceState({}, document.title, location.href+"&history=-1");
var _scrollTop = $("body").scrollTop();
var _bodyHeight = $("body").height();
sessionStorage.setItem('list',$('#list').html());
sessionStorage.setItem('scrolltop',_scrollTop);
sessionStorage.setItem('bodyheight ',_bodyHeight);
});
if(window.location.search.indexOf('history=-1') > 0)
{
$('#list').html(sessionStorage.getItem('list'));
$("body").height(sessionStorage.getItem('bodyheight'));
$("body").scrollTop(sessionStorage.getItem('scrolltop'));
history.replaceState({}, document.title, location.href.replace('&history=-1',''));
}
else
{
ajaxdata(1);
}
参考
- ajax与HTML5 history pushState/replaceState实例 « 张鑫旭-鑫空间-鑫生活
- pjax