Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 动态浮动菜单问题_Javascript_Jquery_Css - Fatal编程技术网

Javascript 动态浮动菜单问题

Javascript 动态浮动菜单问题,javascript,jquery,css,Javascript,Jquery,Css,当窗口向下滚动超过160像素时,我想使菜单固定在顶部,但如果主体内容太短,它将成为一个无限循环,因为如果我向下滚动超过160像素,菜单将固定,这意味着滚动高度将变为160像素以下,所以脚本将使菜单相对向后,如何解决这个问题 HTML <div id="header">header</div> <div id="content">content</div> CSS body { margin: 0; padding: 0; } #

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

HTML

<div id="header">header</div>
<div id="content">content</div>
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;
}

在添加“固定到菜单的位置”时,还为内容添加paddin top(padding top值等于页眉高度+页眉顶部和底部填充)

JS:


此处不需要任何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;
}
$(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');
    }
});
#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;
}