开发者问题收集

为什么导航栏滚动后背景颜色没有改变?

2016-11-20
80

我试图让导航栏的背景颜色在导航栏到达页面的“关于”部分时从透明变为蓝色。根据控制台的调用,滚动后, scroll_start 变得大于 aboutOffSetTop ,但导航栏颜色没有改变。为什么会发生这种情况?我该如何解决这个问题?

HTML:

<div id="titleSection"> 
    <div class="nav_bar">
        <ul> <li> <a href="index.html">HOME</a> </li>
        <li> <a href="transportation.html">TRANSPORTATION</a> </li> 
        <li> <a href="crafts.html">SHOPS</a> </li>
        <li> <a href="activities.html">EVENTS</a> </li>
        <li> <a href="food.html">FOOD</a> </li>
        </ul>
    </div>
</div>

<div class="about">
    <p> Text here </p>
</div>

CSS:

.nav_bar {
  transition: 1s;
  background-color: transparent;
}

JavaScript:

$(document).ready(function() {
  var scroll_start = 0;
  var aboutOffSetTop = $('.about').offset().top;
  $(document).scroll(function() {
    scroll_start = $(window).scrollTop();
    if(scroll_start > aboutOffSetTop) {
      $('.nav').css('background-color', 'rgba(34,34,34,0.9)');
    } else {
      $('.nav').css('background-color', 'transparent');
    }
  });
});
1个回答

将此部分:

if(scroll_start > aboutOffSetTop) {
            $('.nav').css('background-color', 'rgba(34,34,34,0.9)');
        } else {
            $('.nav').css('background-color', 'transparent');
}

更改为此:

if(scroll_start > aboutOffSetTop) {
            $('.nav_bar').css('background-color', 'rgba(34,34,34,0.9)');
        } else {
            $('.nav_bar').css('background-color', 'transparent');
}
AndrewL64
2016-11-20