简体   繁体   中英

Fix menu bar at top of page once header has been scrolled past

Firstly I apologise if this is too open-ended a question.

I am aware of making the header of a web page static so it is always visible at the top of the viewport and the content passes beneath it as you scroll down. This can be achieved purely with css.

I was wondering how you would achieve letting the header scroll off the page but leave a horizontal menu bar static at the top. http://www.forexfactory.com is a perfect example of this.

I see it calls a JavaScript function onHeaderComplete.execute() which I assume applies extra css style to the nav bar when the header scrolls off but I'm unsure of how it works. Any basic explanation appreciated as my JavaScript skills are relatively limited.

I just answered similar question. CHECK THIS QUESTION

$(function(){
        // Check the initial Poistion of the Sticky Header
        var stickyHeaderTop = $('#stickyheader').offset().top;

        $(window).scroll(function(){
                if( $(window).scrollTop() > stickyHeaderTop ) {
                        $('#stickyheader').css({position: 'fixed', top: '0px'});
                        $('#stickyalias').css('display', 'block');
                } else {
                        $('#stickyheader').css({position: 'static', top: '0px'});
                        $('#stickyalias').css('display', 'none');
                }
        });
  });

DEMO

You can write like this:

$(window).scroll(function() {
    if ($(this).scrollTop() > 50) {
         $('div').addClass('fix');
    } else {
         $('div').removeClass('fix');
    }
});

CSS

.fix{
    position:fixed;
    top:0;
    left:0;
    right:0;
    margin:0;
}

Check this http://jsfiddle.net/a42qB/

You could also do it with pure CSS by creating your menu twice. It's not ideal but it gives you the opportunity have a different design for the menu once it's on top and you'll have nothing else than CSS, no jquery:

<div id="hiddenmenu">
 THIS IS MY HIDDEN MENU
</div>
<div id="header">
 Here is my header with a lot of text and my main menu
</div>
<div id="body">
 MY BODY
</div>

And then have the following CSS:

#hiddenmenu {
position: fixed;
top: 0;
z-index:1;
 }
#header {
top: 0;
position:absolute;
z-index:2;
 }
#body {
padding-top: 80px;
position:absolute;
z-index: auto;
 }

Here is a fiddle for you to see: https://jsfiddle.net/brghtk4z/1/

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