2014-02-06 63 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; 
}