我有这个代码在滚动时更改背景颜色,但它只是从“开始颜色”变为“结束颜色”,是否可以在它们之间包含另一种颜色?
$(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 { }
});
});
答案 0 :(得分:2)
已更新:有五种背景颜色。
请执行以下操作:
$(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()值调用它们。
答案 1 :(得分:1)
使用以下脚本创建随机颜色代码..
var colorcode= 'rgb('
+ (Math.floor(Math.random() * 256)) + ','
+ (Math.floor(Math.random() * 256)) + ','
+ (Math.floor(Math.random() * 256)) + ')';