2012-03-31 74 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之間來計算一個新的顏色。