滚动时如何防止此导航栏的高度增加?

时间:2014-12-22 13:04:28

标签: javascript jquery html css navbar

我有一个使用jQuery定位的浮动水平导航栏。当页面静止时,它是完美的,但是一旦我开始滚动,导航栏的高度就会增加,我不确定为什么。

I've a JSFiddle here to show the unwanted effect

这里是html

<div id="stickyribbon">
    <ul>
        <li><a href="1_Lesson.html" target="_blank">Week1</a>
        </li>
        <li><a href="2_Lesson.html" target="_blank">Week2</a>
        </li>
        <li><a href="3_Lesson.html" target="_blank">Week3</a>
        </li>
        <li><a href="4_Lesson.html" target="_blank">Week4</a>
        </li>
        <li><a href="5_Lesson.html" target="_blank">Week5</a>
        </li>
        <li><a href="6_Lesson.html" target="_blank">Week6</a>
        </li>
    </ul>
</div>

这里是css

#stickyribbon {
    width:800px;
    background: orange;
    border-radius: 5px;
}
#stickyribbon ul {
    display:table;
    width:100%;
    list-style-type: none;
}
#stickyribbon li {
    display:table-cell;
    font-size: 16px;
    font-weight: bold;
    vertical-align:middle;
}
#stickyribbon li a {
    display:block;
    color: #fff;
    text-decoration: none;
}
#stickyribbon li a:hover {
    color: yellow;
}

最后是JavaScript

$(function () {
    var stickyRibbonTop = $('#stickyribbon').offset().top;

    $(window).scroll(function () {
        if ($(window).scrollTop() > stickyRibbonTop) {
            $('#stickyribbon').css({
                position: 'fixed',
                top: '0px'
            });
        } else {
            $('#stickyribbon').css({
                position: 'static',
                top: '0px'
            });
        }
    });
});

我感激任何指导,因为我完全难过。 TIA

2 个答案:

答案 0 :(得分:1)

您可以将CSS更改为以下内容,关键是您需要正确定义定位,填充和边距以在两种状态下建立布局:

Demo Fiddle

#stickyribbon {
    width:800px;
    background: orange;
    border-radius: 5px;
    position:static;
    top:0;
    margin:15px 0;
}
#stickyribbon ul {
    display:table;
    width:100%;
    list-style-type: none;
    padding:0;
    margin:0;
}
#stickyribbon li {
    display:table-cell;
    font-size: 16px;
    font-weight: bold;
    vertical-align:middle;
    padding:0 40px;
}
#stickyribbon li a {
    display:block;
    color: #fff;
    text-decoration: none;
}
#stickyribbon li a:hover {
    color: yellow;
}

答案 1 :(得分:0)

div #stickyribb有一些余量,当页面滚动时,重新绘制div以填充该边距。 加 余量:0; 到#stickyribbon ul和#stickyribbon li。