【发布时间】:2020-03-21 10:58:13
【问题描述】:
我希望当用户向下滚动到某个元素下方时,我的侧边栏会改变颜色。我希望背景从透明变为黑色,但慢慢地,看起来它正在褪色为黑色。下面我有一些旧代码,我正在尝试修改它。
$(window).on("load",function() {
$(window).scroll(function() {
var windowBottom = $(this).scrollTop() + $(this).innerHeight();
$(".project").each(function() {
/* Check the location of each desired element */
var objectBottom = $(this).offset().top + $(this).outerHeight();
/* If the element is completely within bounds of the window, fade it in */
if (objectBottom < windowBottom) { //object comes into view (scrolling down)
if ($(".sidebar").css("background-color","transparent")) {$(".sidebar").css("background-color","black");}
} else { //object goes out of view (scrolling up)
if ($(".sidebar").css("background-color","black")) {$(".sidebar").css("background-color","transparent");}
}
});
}).scroll(); //invoke scroll-handler on page-load
});
侧边栏的背景是透明的,但是当您在带有图像的 div 下方滚动时,我需要将背景变为黑色。它会这样做,但它只是突然变黑。如何实现淡化效果?我尝试了 .fadeIn 和 .fadeOut 但整个侧边栏以及菜单项都会淡入淡出。我还尝试了 .animate() 但它不适用于背景颜色。我错过了一些简单的东西吗?下面是 CSS。
.sidebar {
height: 100%;
width: 130px;
margin-top: 34px;
position: fixed;
z-index: 1;
background-color: transparent;
overflow-x: hidden;
padding-top: 35px;
}
.sidebar a {
padding: 20px 8px 20px 16px;
text-decoration: none;
font-size: 18px;
color: whitesmoke;
display: block;
}
.sidebar a:hover {
color: #f1f1f1;
}
@media screen and (max-width:1000px) {
.sidebar {
visibility: hidden;
}
}
【问题讨论】:
-
最好的办法是放置一个额外的 div 覆盖淡入淡出元素的区域。然后你淡入/淡出那个元素。否则,没有简单的跨浏览器方法来为背景颜色设置动画。如果你不喜欢这个,谷歌背景颜色动画库。