Changing background color based on page position

前端 未结 2 1482
渐次进展
渐次进展 2021-01-28 21:01

I juste want to change the background color based on the scroll. Red to blue for exemple...

This code works but how can I change the grey to a color ?

ht

相关标签:
2条回答
  • 2021-01-28 21:06
    $(document).ready(function(){       
            var scroll_pos = 0;
            $(document).scroll(function() { 
                scroll_pos = $(this).scrollTop();
                if(scroll_pos > 210) {
                    $("body").css('background-color', 'blue');
                } else {
                    $("body").css('background-color', 'red');
                }
            });
        });
    
    0 讨论(0)
  • 2021-01-28 21:32

    To fade between colors, you can adjust your code slightly to fade between the channels rather than setting all three to the same value. Based on your blue to red example, see the updated fiddle: http://fiddle.jshell.net/j6tc4e9f/

    $(document).ready(function(){
        $(document).scroll(function() {
            var alpha = Math.min(0.0 + 0.4 * $(this).scrollTop() / 210, 0.9);
            var channel = Math.round(alpha * 255);
            var channel2 = 255 - Math.round(alpha * 255);
            $("body").css('background-color', 'rgb(' + channel + ',' + 00 + ',' + channel2 + ')');
        });
    });
    
    0 讨论(0)
提交回复
热议问题