HTML/Javascript: remember scroll independent of the window size

走远了吗. 提交于 2019-12-05 02:00:56

If my assumption is right that the relative scrollTop value in relation to the document height is always the same, the problem could be solved rather simply.

First set a cookie with the read percentage:

var read_percentage = document.body.scrollTop / document.body.offsetHeight;
document.cookie = 'read_percentage=' + read_percentage + '; expires=Thu, 2 Aug 2021 20:47:11 UTC; path=/'

On the next page load you can restore the position by setting the scrollTop value on the body:

var read_percentage = read_cookie('read_percentage');
document.body.scrollTop = document.body.offsetHeight * read_percentage

Note that read_cookie is not a browser function. You have to implement it. Example can be found on http://www.quirksmode.org/js/cookies.html

I tested this on a large page and it worked quite fine.

Aaaaaaand my version is late... again... but at least I have a demo:

My method also uses percents (scroll position / (scroll height - container height))

http://jsfiddle.net/wJhFV/show

$(document).ready(function(){
    var container = $("#container")[0];
    container.scrollTop =
        Number(localStorage["currentPosition"]) *
        (container.scrollHeight - $(container).height())

})

$("#container").scroll(function(){
    console.log("set to: ")
        console.log(
        localStorage["currentPosition"] =
            (this.scrollTop) /
            (this.scrollHeight - $(this).height())
        );
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!