简体   繁体   中英

fixed horizontal navigation menu upon scroll

I'm still relatively new to the world of programming and I am currently attempting to create a website with a horizontal navigation menu that sticks to the top of the page when scrolled down. For example I want to create something such as the menu on http://www.w3schools.com/html/ The menu is a list inside a div which itself inside another div. I tried to change the style of the enclosing div to fixed when the page is scrolled down with some javascript but this is very glitchy and doesn't work effectively. Is there any other way I can do this?

This is the Javascript I am using at the bottom of the html file and the css just changes to position : fixed;

<script type="text/javascript">
var header = $("#menu-wrapper");
var headerY = header.offset().top;
$(document).scroll(function () {
var y = $(document).scrollTop();

if (y >= headerY) {
    header.addClass('fixed');
} else {
    header.removeClass('fixed');
}
});`
</script>

The required view can be achieved using simple CSS3 , no need of JavaScript at initial level !

Working Demo

CSS code :

#cssmenu {
   position:fixed;
   top: 0;
   margin:auto;
   left: 0;
   right: 0;
   width: 100%;
   height: 50px;
   background-color: #4861A3;
}
$(document).ready(function() {
    $(window).scroll(function () {
       var scroll = $(this).scrollTop();
       var topDist = $("your container Selector").position();
       if (scroll > topDist.top) {
          $('Your Menu Seloctor').css({"position":"fixed","top":"0"});
       } else {
          $('Your Menu Seloctor').css({"position":"static","top":"auto"});
       }
   });

});

Above code working for fixed Menu on Scroll using Jquery. This code working even if your Navigation in middle of the page.

The question requires to give a little use of JQuery to get the desired output and also contains different Design style! hence adding another Answer!

Here is working Demo

JQuery Code :

$("document").ready(function(){

        $(window).scroll(function () {
            if ($(this).scrollTop() > 136) {
                $('.nav-container').addClass("f-nav");
            } else {
                $('.nav-container').removeClass("f-nav");
            }
        });

    });

Important CSS :

.f-nav{ z-index: 9999; position: fixed; top: 0; width: 100%;} /* this make our menu float top */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM