代码之家  ›  专栏  ›  技术社区  ›  Joe Borg

页眉Div位置固定在页面顶部,但加载时会在页面顶部显示一个Div

  •  1
  • Joe Borg  · 技术社区  · 11 年前

    我一直在想办法解决这个问题。三个Div,上面是Advert Div,下面是Header Div,最下面是Content Div。在pg加载时,我打算显示广告div,但在滚动时,我希望将标题div保持在固定位置,即顶部:0px,即页面顶部的内容。

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

    我也意识到三个div相互重叠的可能性,在滚动时,使用jquery,我将隐藏advertdiv,当然,头部div将移动到顶部并保持其位置固定属性。

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

    2 回复  |  直到 11 年前
        1
  •  1
  •   Tony    11 年前

    您可以执行以下操作(使用您的示例):

    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%;
    }
    

    希望有助于:)

        2
  •  0
  •   Benjamin    11 年前

    这是密码

    $(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-con fixed

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

    FINAL DEMO