【问题标题】:How do I gradually change the color of navbar on scroll?如何逐渐改变滚动导航栏的颜色?
【发布时间】:2016-10-15 14:04:17
【问题描述】:

我有一个透明的导航栏,我想逐渐改变颜色,直到它在 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>

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

【问题讨论】:

    标签: jquery css html navbar nav


    【解决方案1】:

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

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

    jsfiddele

    【讨论】:

      【解决方案2】:

      是的。当然可以做到.. 看看这个.. 一旦你完成滚动 div 并带有文本 Scroll me ... ,它就会使你变得不透明。

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

      $(document).scroll(function() {
        var dHeight = $("#nav1").height();
        var alpha = (($(this).scrollTop() / dHeight ) / 10);
        $('#changeBg').css('background', 'rgba(53,145,204,' +(alpha * 2)  + ')');
      });
      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;
      }
      <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>

      【讨论】:

      • 请将其标记为正确并投票@hyphynutcookie
      【解决方案3】:

      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() + ')');
        }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-23
        • 1970-01-01
        • 2010-12-17
        • 2014-07-05
        • 2017-02-03
        相关资源
        最近更新 更多