如何在滚动时逐渐更改导航栏的颜色?

时间:2016-06-14 17:44:02

标签: jquery css html5 navbar nav

我有一个透明的导航栏,我想逐渐改变颜色,直到它最终变得不透明,因为它从div下方经过。我有这个:



$(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>
&#13;
&#13;
&#13;

...到目前为止,但不是让页面的整个高度变得不透明,我希望它在达到div的底部后变得不透明,任何人都可以帮助我吗?提前致谢

3 个答案:

答案 0 :(得分:1)

这里我获得了div的高度。因此,您的nav现在将在您需要的滚动时变得不透明。

这里我附上小提琴。希望这会对你有所帮助。

jsfiddele

答案 1 :(得分:0)

Is this the one you expecting?            

            
  • 第1项
  •         
  • 第2项
  •         
  • 第3项
  •       
                                滚动我......         

           

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;
}

$(document).scroll(function() {
  var dHeight = $(this).height()-$(window).height();
  if (dHeight >= $(this).scrollTop()) {
    $('nav').css('background', 'rgba(53,145,204,' + $(this).scrollTop() + ')');
  }
});

答案 2 :(得分:0)

烨。当然可以这样做..检查一下..一旦你用文本滚动你的div滚动我就会让你变得不透明......

如果我误解了你的问题,请善意纠正我。

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