固定页眉在滚动页面后跳动

3

我发现有几个类似的问题,但是都不能帮助我。当我滚动页面时,标题/导航栏与页面不会“平稳”移动。在我到达页面下方的一定位置后,标题会“跳跃”,但之后就没问题了。 我有以下代码用于固定标题:

$(window).scroll(function(){
    if ($(window).scrollTop() >= 147) {
    $("#top_nav").addClass("fixed");
    $("#top_nav").css("position", "fixed");
    $("#top_rule").hide();
    $("#bottom_rule").hide();
    } 
    else {
    $("#top_nav").removeClass("fixed");
    $("#top_nav").css("position", "initial");
    $("#top_rule").show();
    $("#bottom_rule").show();
    }
 });

我的CSS:

.fixed {
    width: 100%;
    background: white;
    border-bottom: 1px solid black;
    box-shadow: 0 0 20px #000000;
    top: 0px;
    padding-top: 15px;
    padding: 10px;
}

我在CSS中没有使用position: fixed,因为由于某种原因它无法正常工作,所以我使用了jQuery来设置固定位置。
我已经将页面的其余部分发布在jsfiddle.net上
http://jsfiddle.net/5n4pF/ 如果我的解释不清楚,请问我并尝试更好地解释 :)
提前致谢
编辑: 当到达147px时,它不能跳跃。它看起来像是“隐藏和显示”。相反,它必须随着页面向下滚动平稳移动。
2个回答

3
你应该将头部定位为绝对位置,并给新闻一个与头部一样高的margin-top。你的position: fixed不起作用是因为你在相对元素内固定了它。它在该元素内固定(这不是你想要的,因为你想把它固定在页面顶部)。 它跳动是因为你将该元素从static更改为fixed。突然间你的布局就多了约53像素的高度,导致它跳动。 在这个fiddle中:http://jsfiddle.net/5n4pF/3/
* {
    margin: 0px;
    padding: 0px;
}

header {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    text-align: center;
}

#black_top {
    background: black;
    font-size: 5px;
    display:block;
    width: 100%;
    height: 5px;
}

#logo_header {
    margin-top: 20px;
}

.list_item {
    list-style-type: none;
    display: inline-block;
    font: 16px Arial;
    padding: 10px 30px 10px 30px;
    text-align: center;
}

#top_nav {
    font: Arial 30px;
    display: block;
     width: 100%;
}

.nav_links {
    text-decoration: none;
    color: black;
}

hr {
    margin-right: 30px;
    margin-left: 30px;
    color: #f00;
    opacity: 0.3;
}

.nav_bullets {
    color: #D6D6D6;
}

::-moz-selection {
    background: #93E6E5;
}

::selection {
    background: #b3d4fc;
}

#news_block {
    /*Chrome & Safari*/
    -webkit-column-count: 3;
    -webkit-column-gap: 40px;
    /*Firefox*/
    -moz-column-count:3;
    -moz-column-gap: 40px;
    margin: 20px;
    position: absolute;
    top: 249px;
    width: 100%;
    box-sizing: border-box;
}

#search_field {
    font-size: 25px;
}

.fixed {
    width: 100%;
    box-sizing: border-box;
    background: white;
    border-bottom: 1px solid black;
    box-shadow: 0 0 20px #000000;
    top: 0;
    position: fixed;
    padding-top: 15px;
    padding: 10px;
}

已经提供了正确的代码,但在某些宽度方面仍存在一些问题。总体而言,代码不太整洁。因此,我会把这部分留给你处理。希望这对你有所帮助。


哦,等一下。我现在明白你的意思了。等一下,我会编辑我的回答。 - Danny van Holten

-1

我今天在处理它,找到了解决方案。将CSS更改为

.fixed-header .main-header {
    display: none;
}

.fixed-header .main-header {
    display: inline;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接