[英]how to remember previous page's scroll position when click back button
有一些問題,導致滾動“contents_container”而不是滾動“body”。
從此,點擊“history.back”忘記滾動position。
我找到了 jquery cookie,但它不起作用。
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When a button is clicked...
$('#submit').on("click", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
這也是。
if (history.scrollRestoration === 'manual') {
history.scrollRestoration = 'auto';
}
這也是。
我真的很想記住頁面的滾動 position。
這是我的 css 代碼,你能解決這個問題嗎?
.contents_container {width: 100%; height: 100%; overflow-y: scroll; position: relative; float:left;}
謝謝你。
我是在 popstate 上完成的,即使在此事件頁面上仍然存在但不可見,您也可以在 'beforeunload' 上實現這一點。 (如果是服務器端渲染)
window.addEventListener('popstate', onLocationChange);
function onLocationChange(e){
const scrollY = window.scrollY || window.pageYOffset;
localStorage.setItem("scrollY", scrollY)
}
window.addEventListener("load", onPageLoad);
function onPageLoad(){
const scrollY = parseInt(localStorage.getItem("scrollY"));
if(scrollY && !isNaN(scrollY)) {
window.scrollTo(0, scrollY)
}
}
對於溢出的容器
window.addEventListener('popstate', onLocationChange);
function onLocationChange(e){
//if(document.location.test() or startsWith() ....
// to fire only on desired pages
const container document.querySelector('.contents_containe');
const scrollTop = container.scrollTop;
localStorage.setItem("container-scrollTop", scrollTop)
}
window.addEventListener("load", onPageLoad);
function onPageLoad(){
const scrollTop = parseInt(localStorage.getItem("container-scrollTop"));
if(scrollTop && !isNaN(scrollTop)) {
const container document.querySelector('.contents_containe');
container.scrollTop = scrollTop;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.