首页 > 解决方案 > 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;
    }
}

标签: jqueryhtmlcss

解决方案


您可以transition在类的 CSS中添加一个,sidebar以便它从一个渐变到另一个。这可能看起来像这样:

transition: background-color 0.5s ease;

通用语法是transition: <property> <duration> <timing-function> <delay>;. 关于过渡的Mozilla 开发人员页面更深入地介绍了如何使用它们。


推荐阅读