我有这段代码可以更改滚动时的背景颜色,但它仅从“开始颜色”更改为“结束颜色”,是否可以在它们之间包含其他颜色?
$(document).ready(function(){
var scroll_pos = 0;
var animation_begin_pos = 0;
var animation_end_pos = $(document).height();
var beginning_color = new $.Color( 'rgb(140,212,208)' );
var ending_color = new $.Color( 'rgb(145,216,247)' ); ;//what color we want to use in the end
$(document).scroll(function() {
scroll_pos = $(this).scrollTop();
if(scroll_pos >= animation_begin_pos && scroll_pos <= animation_end_pos ) {
// console.log( 'scrolling and animating' );
//we want to calculate the relevant transitional rgb value
var percentScrolled = scroll_pos / ( animation_end_pos - animation_begin_pos );
var newRed = beginning_color.red() + ( ( ending_color.red() - beginning_color.red() ) * percentScrolled );
var newGreen = beginning_color.green() + ( ( ending_color.green() - beginning_color.green() ) * percentScrolled );
var newBlue = beginning_color.blue() + ( ( ending_color.blue() - beginning_color.blue() ) * percentScrolled );
var newColor = new $.Color( newRed, newGreen, newBlue );
//console.log( newColor.red(), newColor.green(), newColor.blue() );
$('body').animate({ backgroundColor: newColor }, 0);
} else if ( scroll_pos > animation_end_pos ) {
$('body').animate({ backgroundColor: ending_color }, 0);
} else if ( scroll_pos < animation_begin_pos ) {
$('body').animate({ backgroundColor: beginning_color }, 0);
} else { }
});
});
最佳答案
更新:有五种背景颜色。
只需执行以下操作:
$(document).ready(function(){
var colorCodes = ['red','blue','green','yellow','orange'];
$(window).on('scroll',function(){
var value = $('body').scrollTop()%5;
$('body').animate({
backgroundColor: colorCodes[value]
}, 100 );
});
});
根据scrollTop()的值更改颜色代码。
获取您自己的颜色代码数组并根据scrollTop() 值调用它们。
关于jquery - 在滚动背景颜色更改期间包括颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15562815/