【问题标题】:How to set the header to fix on screen when scroll down?向下滚动时如何将标题设置为固定在屏幕上?
【发布时间】:2015-10-22 15:48:21
【问题描述】:

这是演示站点:

http://www.kraphicstudio.com/LLR/index.html

如果你向下滚动网站直到横幅消失,你会发现菜单栏

“关于赞助商查询注册捐赠活动”

会粘在屏幕上。

我试过了

#menu {
 position: fixed;
}

但它只能修复元素而不是在某些条件下修复元素。演示站点中的效果怎么做?非常感谢。

【问题讨论】:

标签: javascript jquery html css layout


【解决方案1】:

你现在已经习惯了,如果你向下滚动而不是你的菜单是这样固定的

var oritop = -100;
$(window).scroll(function() {
    var scrollt = $(this).scrollTop();
    var elm = $(".scrollTopWindow");
    if(oritop < 0) {
        oritop= elm.offset().top;
    }
    if(scrollt >= oritop) {
        elm.css({"position": "fixed", "top": 0, "left": 0,"right":0});
    }
    else {
        elm.css("position", "static");
    }
});
body{height:2000px}
.scrollTopWindow {
    background-color: red;
    height: 40px;
    color: white;
    padding:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Some Content here <br>Some Content here <br>Some Content here <br>Some Content here <br>Some Content here <br>Some Content here <br>Some Content here <br>Some Content here <br>Some Content here <br>Some Content here <br>Some Content here <br>Some Content here <br>Some Content here <br>Some Content here <br>Some Content here <br>
<div class = "scrollTopWindow">
    Scroll top window and fix me !
</div>

Source code is

【讨论】:

    【解决方案2】:

    使用滚动您可以检查,在窗口达到特定高度后添加固定到您的标题

        $(window).scroll(function () {
           var height = 30;
           var selector = $('header');
            if($(this).scrollTop() >= height){
                selector .addClass('fixedHead');    
            }else{
                selector .removeClass('fixedHead');
            }
    
        });
    

    CSS

        .fixedHead{
            position: fixed;
            width: 100%;
            top: -30px;
            left: 0;
        }
    

    我认为这可能有效

    【讨论】:

      【解决方案3】:

      您可以通过以下链接查看。

      http://jsfiddle.net/elcreador419/xJXZr/

          var navPos = $('#nav').offset().top;
      
      $(window).scroll(function () {
          var fixIT = $(this).scrollTop() >= navPos;
          var setPos = fixIT ? 'fixed' : 'relative';
          var logoSH = fixIT ? 'show' : 'hide';
          $('#nav').css({
              position: setPos
          });
          $('#mini-logo')[logoSH](300);
      });
      

      【讨论】:

      • offset top 有时效果不好,需要具体说明上面元素的实际高度
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多