1.背景
在H5页面的电商系统中往往会有以下需求:
点击分类等跳转到商品列表页,点击某个商品之后再返回到列表页,返回列表页面的时候能记住之前浏览的位置:
2.方案:
我们需要哪些数据?
- 当前页数
- 当前已经加载的数据
- 当前滚动的高度
2.1 cookies和localstorage
- 在页面滚动的过程中将滚动的距离和当前页数记录下来(也有设置锚点的)。
- 加载新数据的时候将页面的数据及当前页数记录下来。
- 将上面三个数据存储到浏览器缓存中,并设计过期时间。
- 从商品详情页回到列表页面的时候,判断是否是从详情页返回的(可以根据 window.location.hash判断)。如果是从详情页返回的,将数据加载到html页面。
- 缓存过期后,清除缓存。
这个方案有2个弊端
- 浏览器必须支持 localstorage(主流的基本上都支持了)
- 缓存失效时间,如果处理不当可能造成数据混乱
2.2 html5的replaceState
history.pushState() 和 history.replaceState() 是什么有兴趣的可以到网上查下
- 创建一个对象用于存储需要的信息
- 在页面滚动的过程中将当前滚动的距离记录下来。
- 加载新数据的时候替换老的数据。
- 点击进入商品详情页之前将当前页数、数据、滚动距离更新到对象中。
- 从商品详情页回到列表页面的时候,$(window).load()判断是否有数据,有就从对象中取,否则ajax请求
- window.history.replaceState({}, “”, page); 清空数据
总上所述,个人比较推荐方案2
现贴上方案2的部分代码,仅供参考
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() - $(document).height() >= -1) {
if (!scrolling) {
curPage++;
showLoading();
setTimeout(function() {
getList(10);
}, 3000);
}
}
});
$(window).load(function() {
//判断如果有history.state.data,说明是从详情页返回的
if (!!(window.history.state && window.history.state.data)) {
$("#loading").hide();
$("#nomore").hide();
$("#loadmore").show(); //隐藏loading,显示 加载更多(为了分页)
dealWithResult(window.history.state); //根据记录的数据显示列表
curPage = window.history.state.curPage;
statedata = window.history.state; //把页面和data赋值给全局变量
window.history.replaceState({}, "", "list.html"); //清空state,防止列表页点返回的时候会回到上一个state
} else {
getList(20);
}
});
function dealWithResult(listdata) {
$("#list").html(listdata.data)
//判断如果是详情页回来,获取上次的滚动条位置
if (!!(window.history.state && window.history.state.data)) {
// 延迟 0.5秒滚动,防止页面中列表还没构建完
setTimeout(window.scroll(0, window.history.state.sh || 0), 500);
}
}
var totalnum = 0;
var statedata = {};
var curPage = 1;
function getList(num) {
var li = '';
for (i = totalnum; i < totalnum + num; i++) {
li += '<li class="goodsDetail"><a href="javascript:void(0);">list' + (i + 1) + '</a></li>';
}
totalnum += num
$("#list").append(li);
statedata.data = $("#list").html();
hideLoading();
}
function showLoading() {
scrolling = true;
$("#loading").show();
}
function hideLoading() {
scrolling = false;
$("#loading").hide();
}
$("#list").on('click', ".goodsDetail", function() {
//所有数据
var data = $("#list").html();
statedata.curPage = curPage
statedata.data = data
statedata.sh = scroll2Top();
var hrefPage = "detail.html";
history.replaceState(statedata, "", "list.html");
window.location.href = hrefPage;
});
//当前滚动条位置
function scroll2Top() {
var scrollTop = 0;
if (document.documentElement && document.documentElement.scrollTop) {
scrollTop = document.documentElement.scrollTop;
} else if (document.body) {
scrollTop = document.body.scrollTop;
}
return scrollTop;
}
v1.5.2