滚动时使div固定在页面上

8
如何在滚动时固定 div?
请看下面的截图:
这张截图是固定在顶部的: enter image description here 而这张截图则是在滚动时固定的: enter image description here 我的意思是,如果固定到顶部后,div 恢复正常(没有 CSS 固定效果)。
请看这张截图,我想要像这样,如果 div 固定在顶部,则回到正常状态(无需 CSS 粘性): enter image description here 这是我的粘性元素:

    @media screen and (min-width: 768px) {
    .sticky {
        position: fixed;
        z-index: 9999;
        display: block;
        background-color: #2069e8;
        width: 100%;
        padding: 10px;
        margin-top: -10px;
        padding-top:10px
    }
    }
    <div class="sticky">            
    <div class="col-sm-2">
    <h2 style="margin:0px; width:250px;"><span class="smallnav menustater" onclick="openNav()"><i class="fa fa-th-list"></i></span> <a href="http://myweb.com" style="color:#ffffff; text-decoration:none; position:absoulute; display:block; margin-top:-33px; margin-left:38px; z-index:5; width:250px; font-weight:bold;">MY WEB</a></h2>
    </div>
    </div>

请帮忙

先谢谢你


你的问题是什么?因为在我这里它完美地工作。 - לבני מלכה
https://dev59.com/y3TYa4cB1Zd3GeqP0vbo - Jesse
您好,感谢回复。我的问题是,如果粘性元素到达顶部后,如何使其恢复正常,即不使用粘性CSS。 - user3075428
您好,我刚刚在上方添加了一张截图图片,以便您更容易地理解。您能帮我吗?谢谢。 - user3075428
2个回答

4
最简单的解决方案是始终将您的div设置为粘性,但增加下面的div的padding-top以确保内容不会隐藏在粘性div下面。
这样可以避免这种情况:

enter image description here

通过将页面内容移动到底部。
演示:https://jsfiddle.net/g9nhq3up/

您好,感谢您的回复。我刚刚在上面添加了一张新的截图图片,您能帮我看看吗? - user3075428
@user3075428 我相信我的解决方案是可行的。我已经添加了一个演示来展示给你。 - Maxime Chéramy

1

您需要将padding-top:设置为内容(而不是导航)
请参考代码:(JSFiddle:https://jsfiddle.net/0fp1qsw3/

 .sticky {
        position: fixed;
        z-index: 9999;
        display: block;
        background-color: #2069e8;
        width: 100%;
        padding: 10px;
        margin-top: 15px;
        padding-top:10px
    }

.content{
  padding-top: 50px;
}
    <div class="sticky">            
    <div class="col-sm-2">
    <h2 style="margin:0px; width:250px;"><span class="smallnav menustater" onclick="openNav()"><i class="fa fa-th-list"></i></span> <a href="http://myweb.com" style="color:#ffffff; text-decoration:none; position:absoulute; display:block; margin-top:-33px; margin-left:38px; z-index:5; width:250px; font-weight:bold;">MY WEB</a></h2>
    </div>
    </div>
    <div class="content">
    <img src="https://material.angular.io/assets/img/examples/shiba1.jpg"/>
    </div>


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