HTML / Javascript:记住滚动与窗口大小无关 [英] HTML/Javascript: remember scroll independent of the window size

查看:104
本文介绍了HTML / Javascript:记住滚动与窗口大小无关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在线阅读书籍的网页。我想将位置保存在文档中,所以当用户恢复阅读时,他会从之前的位置开始。



我可以使用滚动像window.pageYOffset,但这取决于浏览器窗口的大小。换句话说,如果你让你的窗口变窄,相同的文本将会以不同的方式滚动(例如参见图像)。

所以我需要上来以独立于窗口大小的方式测量滚动。任何想法?



注意:我只需要这个工作在基于mozilla的浏览器上。



预先致谢

解决方案

如果我的假设是正确的,即与文档高度相关的相对scrollTop值始终相同,则可以简单地解决问题。



首先使用读取百分比设置一个cookie:

  var read_percentage = document.body .scrollTop / document.body.offsetHeight; 
document.cookie ='read_percentage ='+ read_percentage +'; expires =星期四,2021年8月2日20:47:11 UTC;路径= /'

在下一页加载时,您可以通过在页面上设置scrollTop值来恢复位置body:

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

请注意,read_cookie是不是浏览器功能。你必须执行它。例子可以在 http://www.quirksmode.org/js/cookies.html



我在一个大页面上测试了它,它工作得很好。


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.

Thanks in advance

解决方案

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.

这篇关于HTML / Javascript:记住滚动与窗口大小无关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆