jquery change background color user scroll

后端 未结 6 1037
南方客
南方客 2020-11-29 02:27

Is it possible with jquery that when a user scrolls down the page that the background animate from 50% white to 90% white or someting?

So first it is the color

6条回答
  •  执笔经年
    2020-11-29 02:34

    Updated, more generic version:

    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[2] - cStart[2]];
    
    $(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(',') +')');
        });
    });
    

    In action

    If you want a smooth, gradiated change when scrolling you should try

    $(document).ready(function(){
        $(document).scroll(function() {
            var alpha = Math.min(0.5 + 0.4 * $(this).scrollTop() / 210, 0.9);
            var channel = Math.round(alpha * 255);
            $("body").css('background-color', 'rgb(' + channel + ',' + channel + ',' + channel + ')');
        });
    });
    

    JSFiddle

提交回复
热议问题