HTML/[removed] remember scroll independent of the

2019-04-22 13:59发布

I've got a webpage for reading books online. I'd like to save the position inside the document so when a user resumes his reading, he starts in the point where he previously was.

I can get the scroll using things like window.pageYOffset, but this depends on the browser window size. In other words, if you make your window narrower, the same text will be at a different scroll (see the image for an example).

So I need to come up with a window-size independent way of measuring scroll. Any ideas?

Note: I only need this to work on mozilla based browsers.

Problem example

Thanks in advance

2条回答
我只想做你的唯一
2楼-- · 2019-04-22 14:29

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())
        );
})
查看更多
闹够了就滚
3楼-- · 2019-04-22 14:30

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.

查看更多
登录 后发表回答