基于滚动更改导航栏上的rgba背景颜色

时间:2014-12-20 00:52:18

标签: jquery twitter-bootstrap

我的页面顶部有一个bootrap固定导航栏。我想根据页面上的滚动位置逐渐平滑地将背景颜色不透明度从0增加到0.75。我怎么能用jquery做到这一点?

滚动前的

.navbar-inverse {
  background: rgba(53,145,204,0);
}

滚动~500px或更好但当前窗口大小的100%

.navbar-inverse {
  background: rgba(53,145,204,0.75);
}

2 个答案:

答案 0 :(得分:4)

你想要达到这样的目标吗?

$(document).scroll(function() {
  var dHeight = $(this).height()-$(window).height();
  if (dHeight >= $(this).scrollTop()) {
    $('nav').css('background', 'rgba(53,145,204,' + $(this).scrollTop() / dHeight + ')');
  }
});
body {
  margin: 0;
}
nav {
  background: rgba(53, 145, 204, 0);
  position: fixed;
  top: 0;
  width: 100%;
}
nav ul > li {
  display: inline-block;
}
.container {
  height: 1000px;
  margin-top: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<nav>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
</nav>
<div class="container">
  <div>
    Scroll me...
  </div>
</div>

答案 1 :(得分:2)

用它来达到类似的效果:

    $(function() {
        //caches a jQuery object containing the header element
        var header = $(".fade-transparent");
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 200) {
                header.removeClass('fade-transparent').addClass("fade-background");
            } else {
                header.removeClass("fade-background").addClass('fade-transparent');
            }
        });
    });


.fade-background {

      background-color: #3591cc;
      background-color: rgba(53,145,204,0.75);

      -webkit-transition: background-color 3s;
    transition: background-color 3s;

}

.fade-transparent {

      background-color: transparent;

      -webkit-transition: background-color 1s;
    transition: background-color 1s;

}