栏固定在顶部,但仅在滚动试图隐藏它时

dgn*_*nin 2 javascript css

我在网络的最高区域有一个菜单,但不在顶部.我希望当用户滚动页面时它保持在顶部,但只有当它会消失时才会消失.如果标题是可见的,我希望它下面的菜单,在一个明显的静态位置.

没有javascript,只能用css吗?我在网站上看到它,但我不记得在哪里.

提前谢谢(对不起我丑陋的英语!);)

gab*_*ish 5

我想这就是你要找的:http://jsfiddle.net/QuVkV/2/

这里是html结构:

<div id='wrapper'>
    <div id='upper'>This is upper content</div>
    <div id='position-saver'>
        <div id='bar'>This is the menu bar</div>
    </div>
    <div id='lower'>This is some content lower than the menu bar</div>
</div>
Run Code Online (Sandbox Code Playgroud)

这是css:

#wrapper {
    width: 100%;
    height: 2000px;
}

#upper {
    width: 100%;
    height: 100px;
}

#position-saver {
    height: 50px;
    width: 100%;
}

#bar {    
    position: static;
    height : 50px;
    width: 100%;
}
Run Code Online (Sandbox Code Playgroud)

这是javascript:

$(document).on('scroll', function(){
    if ($('#bar')[0].offsetTop < $(document).scrollTop()){
        $("#bar").css({position: "fixed", top:0});            
    }
    if ($(document).scrollTop() < $("#position-saver")[0].offsetTop){
        $("#bar").css({position: "static", top: 0});           
    }            
});
Run Code Online (Sandbox Code Playgroud)