jquery - jquery:当div达到一定高度时更改背景颜色
问题描述
当用户向下滚动到某个元素下方时,我希望我的侧边栏改变颜色。我希望背景从透明变为黑色,但要慢慢地使它看起来像褪色成黑色。下面我有一些旧代码,我正在尝试修改它。
$(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;
}
}
解决方案
您可以transition
在类的 CSS中添加一个,sidebar
以便它从一个渐变到另一个。这可能看起来像这样:
transition: background-color 0.5s ease;
通用语法是transition: <property> <duration> <timing-function> <delay>;
. 关于过渡的Mozilla 开发人员页面更深入地介绍了如何使用它们。
推荐阅读
- reactjs - 微前端、Web 组件和共享库
- java - 保存已经运行的侦听器容器并在新设置失败时回滚
- c++ - 使用 VS2015 构建 Dlib c++ 时构建失败
- powershell - 搜索 ADAccount 未返回 EmployeeID/EmployeeNumber
- javascript - 如何让我的服务器获取 js 文件而不是再次获取 html?
- mysql - 从单个数据源并行运行代码
- javascript - 如何从内部函数中获取值
- powershell - 使用 PowerShell 总结平均信息
- jsf - ckeditor tabSpaces在项目符号列表java中不起作用
- pyspark - 如何为同一回答多次取值,并且需要为每个值创建一列