我有一个网页,每次刷新时都会动态加载.如果用户正在编辑网页中的条目,则钻取到链接中.然后尝试按后退按钮,或者同时按下与上一页对应的选项卡,如何在单击后退按钮或对应同一页面的选项卡时保存垂直滚动条位置并将它们返回到相同位置.
我试过这个,但它只适用于非动态加载的页面.
How can I retain the scroll position of a scrollable area when pressing back button?
最佳答案 您可以在链接的问题中使用相同的功能,但是听取滚动事件而不是页面卸载事件.这样,每次用户滚动时,滚动位置将被更新和存储.
由于页面是动态加载的,因此您可以在加载内容后触发事件,这将导致页面滚动:
$.get('/resource').done(function(){
// Render...
// Add a trigger after the content is loaded and rendered
$(window).trigger('content:loaded');
}
var prevScrollHorizontal = 0;
var prevScrollVertical = 0;
$(function() {
$("div#element").scroll(function() { // Listens for scroll events
var currentHorizontal = $(this).scrollLeft();
var currentVertical = $(this).scrollTop();
if(prevScrollHorizontal != currentHorizontal) {
prevScrollHorizontal = currentHorizontal;
localStorage.setItem("scrollPositionHorizontal", currentHorizontal);
// Scrolled horizontally
}
if(prevScrollVertical != currentVertical) {
prevScrollVertical = currentVertical;
localStorage.setItem("scrollPositionVertical", currentVertical);
// Scrolled vertically
}
});
// Listen for the 'content:loaded' event triggered above
$(window).on('content:loaded', function() {
if(localStorage.scrollPositionVertical) {
$("div#element").scrollTop(localStorage.getItem("scrollPositionVertical"));
}
if(localStorage.scrollPositionHorizontal) {
$("div#element").scrollLeft(localStorage.getItem("scrollPositionHorizontal"));
}
});
});
您可以使用window.location.pathname值分隔不同的存储滚动对象以区分它们:
$(function() {
$(window).scroll(function() { // Listens for scroll events
var scrollPosition = $("div#element").scrollTop();
// Uses the pathname to set the scroll value
localStorage.setItem("scrollPosition_"+window.location.pathname, scrollPosition);
});
if(localStorage.scrollPosition) {
// Uses the pathname to get the scroll value
$("div#element").scrollTop(localStorage.getItem("scrollPosition_"+window.location.pathname));
}
});