jquery - 在滚动背景颜色更改期间包括颜色

标签 jquery css colors background

我有这段代码可以更改滚动时的背景颜色,但它仅从“开始颜色”更改为“结束颜色”,是否可以在它们之间包含其他颜色?

example

    $(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() 值调用它们。

Working Fiddle

关于jquery - 在滚动背景颜色更改期间包括颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15562815/

相关文章:

html - Flex 增长直到溢出滚动,侧边栏中的页脚组件父高度为 100%

java - 使用开关盒油漆组件选择颜色(下拉列表中的值)

javascript - 关于 Ajax 便捷方法和错误处理的 jQuery 最佳实践是什么?

jquery - 布局适用于 jsfiddle,不适用于浏览器

javascript - HTML 表单,仅从三个单选按钮中选择一个

html - 根据高度排列列

javascript - 使用 list.js 不会显示 HTML5 音频

javascript - 谷歌地图信息框位置

php - PHP 函数 : brightness(); making RGB colors darker/brighter 需要帮助

html - Firefox 和 IE 中线性渐变的代码