[英]Change Background-color on scroll
我想創建一個類似於下一頁http://readymag.com/的效果 ,其中背景顏色根據滾動位置而變化,但不知道如何去做,我無法理解他們的代碼。
我已經看到一些從1種顏色變為另一種顏色的例子,但我不確定如何使用多種顏色。 (我希望能夠指定每種顏色)
任何幫助將不勝感激。
邁克爾。
這是一個簡單的方法:
HTML
<body onscroll="scroll()">
...
</body>
JavaScript的
// HSL Colors
var colors = [
[0, 100, 50],
[113, 75, 25],
[240, 87, 40],
[328, 24, 40]
],
el = document.getElementsByTagName('body')[0], // Element to be scrolled
length = colors.length, // Number of colors
height = Math.round(el.offsetHeight / length); // Height of the segment between two colors
function scroll() {
var i = Math.floor(el.scrollTop / height), // Start color index
d = el.scrollTop % height / height, // Which part of the segment between start color and end color is passed
c1 = colors[i], // Start color
c2 = colors[(i+1)%length], // End color
h = c1[0] + Math.round((c2[0] - c1[0]) * d),
s = c1[1] + Math.round((c2[1] - c1[1]) * d),
l = c1[2] + Math.round((c2[2] - c1[2]) * d);
el.style['background-color'] = ['hsl(', h, ', ', s+'%, ', l, '%)'].join('');
}
工作示例: http : //jsbin.com/elolud/2/edit
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.