滚动后为什么导航栏不会改变其背景颜色?

时间:2016-11-20 19:10:07

标签: javascript html css navbar

当导航栏到达我页面的“关于”部分时,我正在尝试将导航栏的背景颜色从透明变为蓝色。根据来自控制台的调用,滚动后,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 个答案:

答案 0 :(得分:2)

更改此部分:

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