2014-02-06 133 views
0

我想在窗口向下滚动超过160像素时将菜单固定在顶部,但如果主体内容太短,它将变成无限循环,因为如果向下滚动超过160像素,菜单将变成固定的,这意味着滚动高度将变成低于160像素,所以脚本会使菜单相对返回,如何解决这个问题。动态浮动菜单问题

Demo

HTML

<div id="header">header</div> 
<div id="content">content</div> 

的JavaScript

$(window).on('scroll', function() { 
    var scroll = $(window).scrollTop(); 

    if (scroll > 160) { 
     $('#header').css('position', 'fixed'); 
    } else { 
     $('#header').css('position', 'relative'); 
    } 
}); 

CSS

body { 
    margin: 0; 
    padding: 0; 
} 
#header { 
    width: 100%; 
    height: 60px; 
    background: black; 
    color: yellow; 
    position: relative; 
    padding: 6px; 
} 
#content { 
    width: 100%; 
    height: 780px; 
    background: gray; 
} 

回答

0

时加入固定到菜单的位置,还添加paddin顶内容(填充顶值等于头高度+头顶部和底部填充)

JS:

$(window).on('scroll', function() { 
    var scroll = $(window).scrollTop(); 

    if (scroll > 160) { 
     $('#content').css('padding-top', '72px'); 
     $('#header').css('position', 'fixed'); 
    } else { 
     $('#content').css('padding-top', '0'); 
     $('#header').css('position', 'relative'); 
    } 
}); 

fiddle

0

你不需要任何javascript这里...所以删除所有js ...并编辑你的css:

#header { 
    width: 100%; 
    height: 60px; 
    background: black; 
    color: yellow; 
    position: fixed; /* make menu header always fixed */ 
    padding: 6px; 
    top:0px; 
} 

#content { 
    width: 100%; 
    height: 780px; 
    margin-top:72px; /* margin top 72px because of header height is 60px + pedding 6px*2 */ 
    background: gray; 
}