开发者

HTML/Javascript: remember scroll independent of the window size

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 开发者_StackOverflow社区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.

HTML/Javascript: remember scroll independent of the window size

Thanks in advance


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())
        );
})


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜