历史推送状态和滚动位置
history pushState and scroll position
当用户使用HTML5 popstate处理程序导航回浏览器历史记录时,我试图检索滚动位置。
我有:
$(document).ready(function () {
$(window).on('popstate', PopStateHandler);
$('#link').click(function (e) {
var stateData = {
path: window.location.href,
scrollTop: $(window).scrollTop()
};
window.history.pushState(stateData, 'title', 'page2.html');
e.preventDefault();
});
});
function PopStateHandler(e) {
alert('pop state fired');
var stateData = e.originalEvent.state;
if (stateData) {
//Get values:
alert('path: ' + stateData.path);
alert('scrollTop: ' + stateData.scrollTop);
}
}
<a id="link" href="page2.html"></a>
当我返回时,我无法检索stateData的值。
我认为这是因为popstate正在检索初始页面加载的值,而不是当超链接被点击时我推送到历史记录的状态。
我怎样才能在返回时获得滚动条的位置?
我自己解决了这个问题:
我们必须在导航到新页面之前覆盖历史堆栈上的当前页面。
这允许我们存储滚动位置,然后在返回时将其从堆栈中弹出:
$('#link').click(function (e) {
//overwrite current entry in history to store the scroll position:
stateData = {
path: window.location.href,
scrollTop: $(window).scrollTop()
};
window.history.replaceState(stateData, 'title', 'page2.html');
//load new page:
stateData = {
path: window.location.href,
scrollTop: 0
};
window.history.pushState(stateData, 'title', 'page2.html');
e.preventDefault();
});
想办法用jQuery让它更有动态性,希望能有所帮助:
$(".lienDetail a").on('click',function(){
history.pushState({scrollTop:document.body.scrollTop},document.title,document.location.pathname);
}
这里没有jQuery的解决方案:
function pushHistory(e){
e = e || window.event;
var target;
target = e.target || e.srcElement;
if (target.className.match(/'blienDetail'b/)){
history.pushState({scrollTop:document.body.scrollTop},document.title,document.location.pathname);
}
}
if (document.body.addEventListener)
{
document.body.addEventListener('click',pushHistory,false);
}
else
{
document.body.attachEvent('onclick',pushHistory);
}
这将为每次点击链接推送历史状态与lienDetail类的结果列表,例如
相关文章:
- 有没有一种方法可以直接从cordova获得滚动位置
- 根据滚动位置动态更改href
- 是否可以使用flexbox显示模型设置元素的滚动位置
- 浏览器持续滚动位置
- Sammy.js缓存和滚动位置时,返回历史
- PHP保持滚动位置
- 按下后退按钮时,如何保持可滚动区域的滚动位置
- 滚动位置 (scrollTop) 硬件是否在浏览器中加速
- 在 React 中创建滚动位置指标
- 关闭移动菜单后恢复滚动位置
- 检测可滚动元素内的滚动位置
- 如何在反应性呈现新帖子时保持滚动位置
- UI 路由器 - 在状态之间转换时记住滚动位置
- 单击下拉列表时保持滚动位置(javascript)
- 保留选项后的滚动位置(单击时)
- js-scrollToEl获取滚动位置
- Backbone.js路由和滚动位置
- 如何更改页眉'的底部边框颜色取决于滚动位置
- 如何精确地获得页面的最大滚动位置
- 导航栏固定底部位置,当到达滚动位置时切换到静态