【问题标题】:div is not staying at the top of page while making position is fixed in html page在html页面中固定位置时,div不会停留在页面顶部
【发布时间】:2015-08-13 05:26:52
【问题描述】:

我正在制作一个与页面固定的(位置固定),但它应该在滚动时始终固定在页面顶部 喜欢这个网站 -

http://www.simplilearn.com/project-management/pmp-certification-training

在此站点中作为查询表单放置在向下滚动时始终保持在顶部,最初位于中间,到达该位置后它将保持在顶部直到页面结束滚动

这是我的风格代码

.right-tab {
position: fixed;
background-color: red;
 z-index:100; 
 top:0;
 left:0;
  }

这是我的身体

 <div >
    <h1>Sample This 
    Will go up while scrolling </h1>
    </div>
    <div class="right-tab">
    <h1>Sample This Will not  go up while scrolling </h1>
    </div>

【问题讨论】:

  • 另外在您提供的示例 css 属性中还定义了 top

标签: javascript jquery html css


【解决方案1】:

https://jsfiddle.net/5ADzD/743/

https://jsfiddle.net/5ADzD/743/embedded/result/

<div class="long">Long Div to enable scrolling</div>

<div id="container">
    <div id="navwrap">NAV WRAP</div>
</div>

JAVA SCRIPT


function fixDiv() {
    var $div = $("#navwrap");
    if ($(window).scrollTop() > $div.data("top")) { 
        $('#navwrap').css({'position': 'fixed', 'top': '0', 'width': '100%'}); 
    }
    else {
        $('#navwrap').css({'position': 'static', 'top': 'auto', 'width': '100%'});
    }
}

$("#navwrap").data("top", $("#navwrap").offset().top); // set original position on load
$(window).scroll(fixDiv);

风格

#container {
    padding: 1000px 0 2500px;
}
#navwrap{
    width: 100%;
    height: 50px;
    background-color: #C00;
}

.long {
    background-image: linear-gradient(top, #eee, #aaa);
    background-image: -moz-linear-gradient(top, #a00, #000);
    color: white;
    height: 2000px;
    padding-top: 50px;
}

【讨论】:

    【解决方案2】:

    请使用以下css

    .right-tab {
        position: fixed;
        background-color: red;
        z-index:100;
        top:0;
    }      
    

    【讨论】:

      【解决方案3】:

      你错过了想要修复的位置

       .right-tab {
              position: fixed;
              background-color: red;
             top:0;
             left:0; // change the axis with your values
                }
      

      【讨论】:

        【解决方案4】:

        也使用 z-index:

        .right-tab {
            position: fixed;
            background-color: red;
            z-index:100;
            top:0;
            }
        

        jsfiddle

        【讨论】:

        • 我试过了,但它仍然停留在初始位置。我想当它滚动时,它应该贴在页面顶部。@Siamak Ferdos
        【解决方案5】:

        不需要两个单独的 DOM 对象(即您的右选项卡类)。只需使用一个元素并使用 javascript/jQuery 来修复它。检查窗口滚动位置和元素位置,以及何时满足条件:

        $(window).scroll(function(){
           if(window.pageYOffset >= $('.right-tab').position().top)
              // Add fixed styling to your .right-tab element here to make it fixed
           else 
              // Remove the fixed styling
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-06-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-13
          • 1970-01-01
          相关资源
          最近更新 更多