繁体   English   中英

尽管窗口高度也保持与页面顶部的滚动距离

[英]Keeping scroll distance from top of page despite window height

我正在根据页面顶部的滚动位置更改页面的背景颜色,但是无论窗口的高度如何,我都希望循环显示所有颜色。 我现在所拥有的严格基于滚动从页面顶部开始的像素数,但是您会看到,这取决于窗口的高度。 我如何修改它以使其始终滚动浏览所有颜色,即使浏览器已调整大小?

到目前为止,我所拥有的: http : //jsfiddle.net/keith/P7ER3/

这是文档的高度: $(document).height()

这是视口的堆: $(window).height()

两个值的差返回可以向下滚动的最大像素数(如果为正):

var max_scroll = $(document).height() - $(window).height();

最后,这将返回0到1之间的数字,以反映滚动量:

var scrollamount;
if (max_scroll > 0.0) {
    scrollamount = $(document).scrollTop() / max_scroll;
} else {
    scrollamount = 0.0;
}

您可以使用此scrollamount,将其始终设置在0到1之间以从中计算出新的颜色。

您可以使用window.outerHeightwindow.pageYOffset之间的percent difference

  window.outerHeight // the pixel height of the browser's frame.

  window.innerHeight // the pixel height of the document within the browser's frame.

  window.pageYOffset  // reflects the current vertical pixel 
                      // location of the top-left corner of the document.

  var perDiff = window.pageYOffset / (window.outerHeight + window.innerHeight);  

  perDiff; // 0 when the scroll is on the top

  perDiff; // 1 when the scroll is on the bottom of the page

可以使用perDiff值代替positionperDiff值始终在0到1之间,以根据该值计算新颜色。

jsfiddle中的PS不能正常工作,因为perDiff是指文档的高度,而不是框架的高度。

尝试更改此行:

scroll_pos = $(document).scrollTop();

对此:

scroll_pos = $(document).scrollTop() % 800;

滚动800像素以上时,取模800的位置基本上会将其重置为零。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM