2012-03-31 75 views
1

我正在根据页面顶部的滚动位置更改我的页面的背景颜色,但我希望循环显示所有颜色,而不考虑页面高度窗户。我现在拥有的是严格基于页面顶部滚动的像素数量,但是您会看到这取决于窗口高度。我怎么能修改这个让它总是滚动浏览所有的颜色,即使浏览器被调整大小?尽管窗口高度保持从页面顶部的滚动距离

我有什么至今: http://jsfiddle.net/keith/P7ER3/

回答

0

您可以使用percent differencewindow.outerHeightwindow.pageYOffset之间。

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 

相反的position,您可以使用perDiff值,也将永远是0和1之间,以从中计算出一个新的颜色。

P.S.在jsfiddle中,这段代码并不适用,因为perDiff指的是文档的高度,而不是指向框架。

0

尝试修改此行:

scroll_pos = $(document).scrollTop(); 

这样:

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

以位置模800将基本重置回零,当你浏览其他800像素。

1

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

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

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

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

最后这将返回0和1之间的nuber反映滚动量:

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

你可以使用这个scrollamount,那么allways将会在0和1之间来计算一个新的颜色。