顶部导航栏(在标题下)在滚动时固定在屏幕顶部

问题描述:

当滚动条位于浏览器顶部时:

When scrollbar is on top browser displays:

HTML:

-------------------------
|   HEADER              |
-------------------------
|   NAVBAR              |
-------------------------
|   body                |
-------------------------

当滚动条向下时,NOW浏览器通常显示:

When scrollbar is down NOW browser normally displays:

HTML:

-------------------------
|                       |
|   body                |
|                       |
-------------------------

但我想有:

-------------------------
|   NAVBAR              |
-------------------------
|                       |
|   body                |
|                       |
-------------------------

我试过:

<div id="navbar">...</div>

CSS:

#navbar {
  position:fixed;
  z-index:1;
}

但这只有在navbar位于顶部位置时才有效。我有顶部的标题...

But this only works if navbar is on the top position. I have the header on top...

DEMO



我在顶部使用了图片,而不是您的问题中提到的HEADER。

DEMO

I have used an image at top instead of the "HEADER" mentioned in your question.

这是我用来固定标题(你的情况下的navbar)的js。

This is the js I have used to make the header(navbar in your case) fixed.

var stickyNavTop = $('#header').offset().top;

$(window).scroll(function() {  
    if ($(window).scrollTop() > stickyNavTop) {
        $('#header').addClass('fixed');
    }
    else {
        $('#header').removeClass('fixed');
    }  
});