滚动过去时,导航栏会粘到屏幕顶部

我正在创建一个网站,我希望当我滚动浏览它时,导航栏将其位置更改为“固定”。

但是有一个问题。 当我改变其位置值时,设计完全混乱。 请参阅www.rowweb.dk/skyline/ – 顺便说一下,我正在使用Bootstrap。

到目前为止,我有以下代码块:

$(window).scroll(function () { winHeight = $(window).height(); if ($(window).scrollTop() > winHeight) { $('.navbar').css('position', 'fixed'); $('.navbar').css('top', '0'); } }); 

有没有人能解决我的问题?

A.沃尔夫是对的。

‘#mainContent’位于.navbar内部,因此它们都固定在顶部,并覆盖.jumbotron元素,以及不可滚动。

把它移到外面.navbar,你应该没问题。

看一下Bootstrap Affix插件: http : //getbootstrap.com/javascript/#affix

这是一个有效的例子: http : //bootply.com/97918


有关
Sticky NavBar onScroll?

将此应用于没有插件的可靠工作。

这是工作jsFiddle。

 $(document).ready(function() { var windowH = $(window).height(); var stickToBot = windowH - $('#menu').outerHeight(true); //outherHeight(true) will calculate with borders, paddings and margins. $('#menu').css({'top': stickToBot + 'px'}); $(window).scroll(function() { var scrollVal = $(this).scrollTop(); if ( scrollVal > stickToBot ) { $('#menu').css({'position':'fixed','top' :'0px'}); } else { $('#menu').css({'position':'absolute','top': stickToBot +'px'}); } }); });​ 

来源: 如何在页面底部构建简单的粘性导航?

$(function(){

 // grab the initial top offset of the navigation var sticky_navigation_offset_top = $('#sticky_navigation').offset().top; // our function that decides weather the navigation bar should have "fixed" css position or not. var sticky_navigation = function(){ var scroll_top = $(window).scrollTop(); // our current vertical position from the top // if we've scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative if (scroll_top > sticky_navigation_offset_top) { $('#sticky_navigation').css({ 'position': 'fixed', 'top':0, 'left':0 }); } else { $('#sticky_navigation').css({ 'position': 'relative' }); } }; // run our function on load sticky_navigation(); // and run it again every time you scroll $(window).scroll(function() { sticky_navigation(); }); // NOT required: // for this demo disable all links that point to "#" $('a[href="#"]').click(function(event){ event.preventDefault(); }); 

});

  function FixedTopMenuOnScroll() { var winHeight = $(".site-header").height();//any image,logo or header above menu winHeight = winHeight - $('.navbar').height(); function checkMenuOnTop() { if ($(window).scrollTop() > winHeight) { $('.navbar').addClass("navbar-fixed-top"); } else { $('.navbar').removeClass("navbar-fixed-top"); } } checkMenuOnTop(); $(window).scroll(function () { checkMenuOnTop(); }); } FixedTopMenuOnScroll();