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

Bar fixed on top, but only if the scroll tries to hide it

本文关键字:滚动 隐藏 顶部      更新时间:2023-09-26

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

没有javascript,只有css可以吗?我在网站上看到它,但我不记得在哪里。

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

我认为这就是你要找的:https://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>

这是 css :

#wrapper {
    width: 100%;
    height: 2000px;
}
#upper {
    width: 100%;
    height: 100px;
}
#position-saver {
    height: 50px;
    width: 100%;
}
#bar {    
    position: static;
    height : 50px;
    width: 100%;
}

这是 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});           
    }            
});

我不确定,但我在许多网站上都见过这种东西。一对一 9gag.com

无论如何,您可以使用 css 的 position 属性。

像这个: JSFiddle

#scroll-me{ 
    width:100%;
     height:100px; 
     background:#333;
     position: fixed;
     top:15px;
     }

带有 scroll-mediv top:15pxposition:fixed使其顶部始终为 15px