在H5页面的电商系统中往往会有以下需求: 点击分类等跳转到商品列表页,点击某个商品之后再返回到列表页,返回列表页面的时候能记住之前浏览的位置:
我们需要哪些数据?
这个方案有2个弊端
history.pushState() 和 history.replaceState() 是什么有兴趣的可以到网上查下
总上所述,个人比较推荐方案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;
}