动态浮动菜单问题

时间:2014-02-06 22:09:40

标签: javascript jquery css

当窗口向下滚动超过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;
}

2 个答案:

答案 0 :(得分:0)

当添加固定到菜单的位置时,也添加paddin-top作为内容(padding-top值等于标题高度+标题顶部和底部填充)

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

答案 1 :(得分: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;
}
相关问题