HTML:

<div class="navigation-bar">
    <div class="item">Home</div>
    <div class="item">About us</div>
    <div class="item">Our Services</div>
    <div class="item">Contact us</div>
</div>


CSS:

.navigation-bar {
    background: black;
    width: 100%;
    margin: 0px;
    height: 70px;
    position: sticky;
}
.f-nav{  /* To fix main menu container */
    z-index: 9999;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
}
.item {
    float: left;
    width: 20%;
    height: 100%;
    color: white;
    text-align: center;
    font-family: ‘Lucida Sans Unicode’, ‘Lucida Grande’, sans-serif;
    font-size: 26px;
    font-weight: 100;
    padding-top: 20px;
}


js文件:

$("document").ready(function ($) {
    var nav = $('.navigation-bar');
    $(window).scroll(function () {
        if ($(this).scrollTop() > 125) {
            nav.addClass("f-nav");
        } else {
            nav.removeClass("f-nav");
        }
    });
});


这是我的代码,但是不起作用。我不知道到达顶部时如何停止导航栏。我认为代码尚可,但是我不知道为什么它不起作用。

最佳答案

    <script>
       $(document).ready(function(){
           $(window).bind('scroll', function() {
           var navHeight = $( window ).height() - 70;
                 if ($(window).scrollTop() > navHeight) {
                     $('nav').addClass('fixed');
                 }
                 else {
                     $('nav').removeClass('fixed');
                 }
            });
        });
    </script>
.fixed {
    position: fixed;
    top: 0;
    height: 70px;
    z-index: 1;
}




<nav>
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Team</a></li>
        <li><a href="#">Contact</a></li>
    </ul>
</nav>

10-01 20:56