2017-03-06 131 views
0

我试图在滚动到某个点时将网页的背景颜色从黑色更改为白色。然后,当您向后滚动并重复该过程时,请变回原位。我有代码,当你滚动到某一点时,添加一个类到块,但我不能让背景颜色改变。这里是jQuery的:滚动时更改页面的背景颜色

<script> 
    $(window).scroll(function() { 

     $('#block-yui_3_17_2_32_1488831533357_14601').each(function() { 

      var topOfWindow = $(window).scrollTop(), 

       bottomOfWindow = topOfWindow + $(window).height(); 

      var imagePos = $(this).offset().top; 

      if (imagePos <= bottomOfWindow - 100 && imagePos >= topOfWindow - 250) { 

       $(this).addClass('color Change'); 

      } else { 

       $(this).removeClass('colorChange'); 

      } 

     }); 

    }); 
</script> 

这里是CSS:

.colorChange { 
    #page { 
     background-color: white; 
     animation-name: colorChange; 
     -webkit-animation-name: colorChange; 

     animation-duration: 2s; 
     -webkit-animation-duration: 2s; 

     animation-timing-function: ease; 
     -webkit-animation-timing-function: ease; 

     animation-iteration-count: 1; 
     -webkit-animation-iteration-count: 1; 

     visibility: visible !important; 
    } 
} 

@keyframes colorChange { 
    0% { 
     background-color: white; 
    } 
    100% { 
     background-color: black; 
    } 
} 

@-webkit-keyframes colorChange { 
    0% { 
     background-color: white; 
    } 
    100% { 
     background-color: black; 
    } 
} 

编辑:我试图改变if语句来改变滚动位置的颜色,而不是补充说,改变颜色的类但它不起作用。另外我怎样才能以这种方式为颜色变化添加一种轻松?下面是编辑的代码:

<script> 
    $(window).scroll(function() { 

     $('#block-yui_3_17_2_32_1488831533357_14601').each(function() { 

      var topOfWindow = $(window).scrollTop(), 

       bottomOfWindow = topOfWindow + $(window).height(); 

      var imagePos = $(this).offset().top; 

      if (imagePos <= bottomOfWindow - 100 && imagePos >= topOfWindow - 250) { 

       $("#page").css("background-color", "black"); 
      } else { 

       $("#page").css("background-color", "white"); 

      } 

     }); 

    }); 
</script> 

回答

0

我认为这将更好看:

body { 
    background: black; /* For browsers that do not support gradients */ 
    background: -webkit-linear-gradient(black, white); /* For Safari 5.1 to 6.0 */ 
    background: -o-linear-gradient(black, white); /* For Opera 11.1 to 12.0 */ 
    background: -moz-linear-gradient(black, white); /* For Firefox 3.6 to 15 */ 
    background: linear-gradient(black, white); /* Standard syntax */ 
} 

但是,如果你真的有你的心脏上设置:

$(document).scroll(function() { 
    rgb = $(document).scrollTop(); // just divide this number by however slow you want the effect to take place. 
    $(document).css("background","rgb(" + rgb + ", " + rgb + ", " + rgb + ")"); 
}); 
+0

#块-yui_3_17_2_32_1488831533357_14601是朝向屏幕底部的元素。当您向下滚动到该点时,我希望页面的背景颜色变为黑色。因此,所有东西都在黑色背景上过去。当您向上滚动元素时,我希望它变回白色。我希望它能够轻松完成。 –

+0

也许会这样做:rgb = $(document).scrollTop() - $(“#block-yui_3_17_2_32_1488831533357_14601”)。scrollTop()。添加一个if来检查rgb是否小于0,如果是,则将rgb赋值为0。 – Neil