重新加载网页并将页面放置在用户所在的位置

时间:2018-06-30 03:20:48

标签: javascript reactjs

在重新加载页面后,有没有一种方法可以使React或javascript处于用户查看的同一位置?到目前为止,location.reload会重新加载页面,但会将页面放置在页面的开头。

3 个答案:

答案 0 :(得分:0)

添加其他true参数以强制重新加载。

document.location.reload(true)

document.location.reload()存储位置

  

普通重装尝试在重装页面后尝试恢复滚动位置,而在强制模式下(当参数设置为true时),新的DOM会使用scrollTop == 0加载。

参考:https://developer.mozilla.org/en-US/docs/Web/API/Location/reload

答案 1 :(得分:0)

您可以添加一个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,因此无法嵌入堆栈代码段)

答案 2 :(得分:0)

您可以使用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
    };
})();