【问题标题】:Header Div position fixed on top of page but on load show a div on top of it标题 div 位置固定在页面顶部,但在加载时会在其顶部显示一个 div
【发布时间】:2014-08-22 13:39:35
【问题描述】:

我一直在尝试找出正确的方法来做到这一点。三个 div,顶部是 Advert Div,底部是 Header Div,最下方是 Content Div。在 pg 加载时,我打算显示广告 div,但在滚动时,我打算将标题 div 保持在固定位置,top:0px,即在页面顶部的内容上方。

我知道在 CSS 中使用固定位置,但我需要它的方式与此属性相矛盾,因为我需要标题 div 在滚动时进一步向上移动直到页面顶部并保持固定位置。

我也知道将所有三个 div 放在彼此之上的可能性,并且在滚动时,使用 jquery 我将隐藏广告 div,并且标题 div 自然会向上移动并保持其位置固定属性.

有什么建议吗? JS Fiddle link here for a quick example

【问题讨论】:

  • 你的小提琴演示是空的,在分享链接之前保存小提琴。
  • 这不是我的朋友。目前有 6 个用户连接

标签: css position fixed


【解决方案1】:

您可以这样做(使用您的示例):

HTML:

<div id="advert-con">
<h3>
    <br />
    <br />
    ADVERT DIV MUST BE OVERLAYED WITH BLACK DIV UPON SCROLLING </h3>
</div>
<!--end advert-con-->
<div id="header-con">
    <h2>
        <br />
        <br />
        HEADER DIV MUST REMAIN VISIBLE ON TOP</h2>
</div>
<!--end header-con-->
<div id="content-con">
    <h4>Content Words Text Context</h4>
</div>
<!--end content-con-->

jquery:

$(document).ready(function () {
   var header = $('#header-con');
   var distanceFromTop;
   if (header.length > 0)
   {
       distanceFromTop = header.offset().top;
   }
   $(window).scroll(function () {
       if (header.length > 0)
       {
           header.toggleClass('sticky-top', $(window).scrollTop() > distanceFromTop);
       }
   });
});

CSS:

.sticky-top {
    position: fixed;
    top: 0;
    width:100%;
}

希望有帮助:)

【讨论】:

  • 感谢您是第一个提出解决方案的人。非常感激。必须是jquery。 css 本身有其局限性
【解决方案2】:

这里是代码

$(document).ready(function () {
    var top_fixed;
    if ($('#header-con').length > 0)
    {
        top_fixed = $('#header-con').offset().top;
    }
    $(window).scroll(function () {
        if ($('#header-con').length > 0)
        {
            $('#header-con').toggleClass('fixed', $(window).scrollTop() > top_fixed);
        }
    });
});

DEMO

更清晰的 CSS

*{
    margin:0;
    padding:0;
}

#advert-con { color:yellow;height:130px;background:blue;width:100%;margin:0px;padding:0px;display:block; }
#header-con { height:170px;background:black;color:#fff!important;margin:0px;padding:0px; }
#content-con { height:700px;background:purple; }

.fixed {
    position: fixed;
    top: 0;
    width:100%;
}

UPDATED DEMO

制作#advert-confixed

.container{
    margin-top:130px;
    display:inline-block;
    width:100%;
}
.container:after{
    display:block;
    clear:both;
    content:"";
}

FINAL DEMO

【讨论】:

  • 很高兴帮助你。
  • 所有的演示都进入 404 页。
猜你喜欢
  • 2016-05-17
  • 1970-01-01
  • 2015-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-04
  • 2015-04-05
  • 2012-09-09
相关资源
最近更新 更多