【问题标题】:Make nav bar sticky使导航栏变粘
【发布时间】:2016-05-19 00:12:19
【问题描述】:

伙计们,

我的网站上有一个导航栏 (http://www.mtscollective.com - 'menu-secondary-wrap'),当用户向下滚动时,我试图让它保持在页面顶部。

我已经测试了几个 jQuery 示例(例如 http://www.hongkiat.com/blog/css-sticky-position/),但它们总是带有自己的 CSS,这似乎干扰了我已经在使用的东西。

对于现有课程,最简单/最好的方法是什么?

谢谢! 马里奥

【问题讨论】:

  • 最好的方法是什么?不。我讨厌那些东西。
  • 第 1 步。编写一个使导航具有粘性的类。编写自己的 css 以使栏永久固定在顶部。使它成为一个可以与现有 css 并存的新类。步骤 2. 根据滚动位置有条件地应用该类。

标签: jquery html css sticky


【解决方案1】:

使用这样的东西(你可以在浏览器控制台F12中查看)

jQuery(window).scroll(function() {
  if (jQuery(this).scrollTop() > 220) {
    jQuery(".menu-secondary-wrap").css({"position": "fixed", "top": 0, "width": "950px"});
  } else {
    jQuery(".menu-secondary-wrap").removeAttr("style");
  }
});

完全没问题

【讨论】:

    【解决方案2】:

    试试这个脚本

    jQuery(document).scroll(function() {
        if (jQuery(this).scrollTop() > 175) {
            jQuery('.menu-secondary-wrap').css({
               'position': 'fixed',
               'top': '0',
               'width': '950px'
            });
        } 
        else {
            jQuery('.menu-secondary-wrap').css('position','static');
        }
    });
    

    【讨论】:

      【解决方案3】:

      执行此操作的最简单方法是使您的标题包装器具有固定的定位和比您网站其余内容的包装器更高的 z-index...

      例子:

      .header-wrapper {
          width: 100%;
          height: 80px;
          position: fixed;
          z-index: 20;
      }
      
      .content-wrapper {
         width: 100%;
         margin-top: 80px; // height of header wrapper.
         z-index: 10;
      }
      

      那么您的 HTML 可能如下所示:

      <div class="header-wrapper">the header</div>
      <div class="content-wrapper">the content</div>
      

      希望这会有所帮助。

      【讨论】:

        【解决方案4】:

        如果您想要一个简单的解决方案。将position: fixed 应用于元素

        body {
          padding-top: 50px;
        }
        
        /* Header span-24, could not find a proper identifier for it */
        .span-24 {
            position: fixed;
            z-index: 99;
            background: #000;
            top: 0;
        }
        

        【讨论】:

          猜你喜欢
          • 2023-02-16
          • 2018-11-02
          • 2019-05-01
          • 1970-01-01
          • 2014-04-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-20
          相关资源
          最近更新 更多