[英]reloading a web page and placing page at same place where user was at
在重新加載頁面后,有沒有一種方法可以使React或javascript在該頁面位於用戶正在查看的同一位置? 到目前為止,location.reload會重新加載頁面,但會將頁面放置在其開始處。
添加其他true參數以強制重新加載。
document.location.reload(true)
document.location.reload()
存儲位置,
普通重新加載嘗試在重新加載頁面后恢復滾動位置,而在強制模式下(當參數設置為true時),新DOM會使用scrollTop == 0加載。
參考: https : //developer.mozilla.org/zh-CN/docs/Web/API/Location/reload
您可以添加scroll
偵聽器,並在滾動時將當前位置保存在sessionStorage
。 然后,在頁面加載時,檢查是否填充了sessionStorage
項目,如果已填充,則將當前滾動位置設置為sessionStorage
保存的數字:
if (sessionStorage.scroll) document.documentElement.scrollTop = sessionStorage.scroll;
window.addEventListener('scroll', () => {
sessionStorage.scroll = document.documentElement.scrollTop;
});
https://jsfiddle.net/1rg37zfd/
(無法嵌入堆棧代碼段,因為它不支持sessionStorage
)
您可以使用localStorage設置值。 然后在您的init()中檢查該用戶最后一次出現的位置。 在該函數中的nextBtn處,我們在此增加頁碼並保存。 我通常使用最小化的同步功能來處理我可能想要執行的任何刷新。
HTML:
<div id='myPage'></div>
JavaScript:
(function () {
"use strict";
var myUI, userData, myPages;
myPages = [
"Home","Page 2","Page 3","Page 4","Page 5"//when the user's page number is summoned with this object, pages will reflect when the syncFunc is ran
];
userData = 0;//out item where we save the users page number
myUI = {
init: () => {
var uData = localStorage.getItem("userData");//we look to see what is the value
if (!uData || uData === null) {
localStorage.setItem("userData", 0);//this only sets the user's page to 0 on first load or if anything goes wrong
}
var pageHolder = document.createElement("h3"),
nextBtn = document.createElement("button");
nextBtn.innerHTML = " > ";
nextBtn.onclick = myUI.nextPage(userData, pageHolder);
pageHolder.innerHTML = myPages[uData];
myPage.appendChild(pageHolder);
myPage.appendChild(nextBtn);
myUI.syncPage(uData, pageHolder, nextBtn);
},
syncPage: (uData, pageHolder) => {//i mean, you could do a whole window reload and it still work, but why do that when you can just sync things on the fly
pageHolder.innerHTML = myPages[uData];
//alert(uData);
},
nextPage: (userData, pageHolder) => {
return () => {
var uData = localStorage.getItem("userData"),//checking for the data when the user hits a button.
newPage;
if (uData >= 4) { newPage = +uData - 4 } else { newPage = +uData + 1; }//iterate by 1 unless we reach our limit
localStorage.setItem("userData", newPage);//save it
uData = localStorage.getItem("userData");//force our script to recognize the newly saved value
setTimeout(() => {//timeout for dramatic effect if desired
myUI.syncPage(uData, pageHolder);//run a function to sync
}, 100);
}
}
};
window.onload = () => {
myUI.init();//initialize
};
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.