当您滚动到某个点时,我试图将网页的背景颜色从黑色更改为白色。然后在向上滚动并重复此过程时返回。我有一些代码,当你滚动到某一点时,它会向一个块添加一个类但我不能让背景颜色改变。这是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 :(得分: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 + ")");
} );