向下滚动页面时多次更改背景颜色

我正在研究这个项目,我正在使用视差滚动创建一个网站。 它应该是一个长的寻呼机。 当您向下滚动页面时,当您到达页面的每个新部分时,背景颜色应该会改变。

我花了几天时间在网上搜索,也在这里搜索stackoverflow,但我没有找到任何可行的方式。

我在堆栈上找到了这个脚本:

var tStart = 100 // Start transition 100px from top , tEnd = 500 // End at 500px , cStart = [250, 195, 56] // Gold , cEnd = [179, 217, 112] // Lime , cDiff = [cEnd[0] - cStart[0], cEnd[1] - cStart[1], cEnd[1] - cStart[0]]; $(document).ready(function(){ $(document).scroll(function() { var p = ($(this).scrollTop() - tStart) / (tEnd - tStart); // % of transition p = Math.min(1, Math.max(0, p)); // Clamp to [0, 1] var cBg = [Math.round(cStart[0] + cDiff[0] * p), Math.round(cStart[1] + cDiff[1] * p), Math.round(cStart[2] + cDiff[2] * p)]; $("body").css('background-color', 'rgb(' + cBg.join(',') +')'); }); }); 

http://jsfiddle.net/dtZDZ/12/这是小提琴

这个脚本正是我想要的,除了我只来回一次改变颜色。 当你向下滚动页面时,我需要它来改变背景颜色4-5次。 另外我希望它在改变颜色时可以顺利过渡,就像在小提琴中一样:)

我希望有人可以帮助我,或者只是指出我正确的方向。

先感谢您

您可以使用css使用渐变背景:

 body { background-color: linear-gradient(red, blue, green, blue, red) } 

向下滚动,您的背景将会改变。 这种方法有点“欺骗”,但是当它到达背景末尾时它会循环。

干得好 :

您可以在colors变量中指定任意数量的colors

 var colors = [ [250, 195, 56], // Gold [250, 0, 0], // Red [0, 250, 0], // Green [0, 0, 250], // Blue [179, 217, 112] // Lime ]; var height = $('body').height() - window.innerHeight; $(document).scroll(function() { var steps = Math.floor(height / colors.length); var position = $(this).scrollTop(); var currentStep = Math.floor(position / steps); if ( currentStep === colors.length ) currentStep = colors.length - 1; var rgb = $("body").css('background-color').replace('rgb(','').replace(')','').replace(/\s/g, '').split(','); var previousColor = colors[currentStep] || colors[0]; var nextColor = colors[currentStep+1] || colors[colors.length-1]; var percentFromThisStep = ( position - ( currentStep * steps ) ) / steps; if ( percentFromThisStep > 1 ) percentFromThisStep = 1; var newRgb = [ Math.floor(previousColor[0] + ( ( nextColor[0] - previousColor[0] ) * percentFromThisStep )), Math.floor(previousColor[1] + ( ( nextColor[1] - previousColor[1] ) * percentFromThisStep )), Math.floor(previousColor[2] + ( ( nextColor[2] - previousColor[2] ) * percentFromThisStep )) ]; $("body").css('background-color', 'rgb('+ newRgb.join(',') +')'); }); 

在这里演示: http : //jsbin.com/ulohif/1/edit