【问题标题】:Leave menu bar fixed on top when scrolled [closed]滚动时将菜单栏固定在顶部[关闭]
【发布时间】:2012-10-27 19:07:07
【问题描述】:

我见过一些网站,当用户向下滚动页面时,会在右侧或左侧弹出一个框...

另外,注意到这个模板:http://www.mvpthemes.com/maxmag/ 设计师做得很好,将导航栏固定在顶部。

现在,这些是如何完成的?我猜它使用 jquery 来获取页面的位置并显示框。

请您指导我到哪里可以找到 sn-p,以便我可以学习做类似的事情。

【问题讨论】:

  • 我已将其关闭为“需要更多关注(太宽泛)”,因为您询问的是两种不同的效果 A)有一个位于页面顶部的导航栏,并且B)当用户向下滚动时,在页面的左侧或右侧打开弹出框。虽然这些可能是相关的,但它们是显着不同的效果,具有不同的实现。您还要求“我在哪里可以找到 sn-p”,这是一个离题的资源请求。但是,如果所有答案都与这样做兼容,则可以将其删除。

标签: jquery css


【解决方案1】:

这种效果通常是通过如下一些jquery逻辑来实现的:

$(window).bind('scroll', function () {
    if ($(window).scrollTop() > 50) {
        $('.menu').addClass('fixed');
    } else {
        $('.menu').removeClass('fixed');
    }
});

这表示一旦窗口滚动超过一定数量的垂直像素,它就会向菜单添加一个类,将其位置值更改为“固定”。

完整的实现细节参见:http://jsfiddle.net/adamb/F4BmP/

【讨论】:

  • 您不能通过以下方式缩短此时间:$('.menu').toggleClass('fixed', $(window).scrollTop() > 50);
  • @MichaelCalkins 是的(另一个是:$('.menu')[($(window).scrollTop() > num ? 'add' : 'remove') + 'Class']('fixed');)但我认为它的编写方式允许最大的可读性。
  • 对于IE,您可能需要在.fixed下添加z-index:1;以确保菜单在顶部。
  • 不幸的是,此实现将触发您在 if 语句中放置的任何功能/交互,每次用户滚动一次单击时触发 6 次,每次单击向下或向上滚动条箭头时触发 9 次。这里多个事件的可能解决方案:stackoverflow.com/questions/9613594/…
  • toggleClass() 缩短了代码,但在类之间切换时会出现奇怪的闪烁。
【解决方案2】:

在本例中,您可以将菜单居中显示。

HTML

<div id="main-menu-container">
    <div id="main-menu">
        //your menu
    </div>
</div>

CSS

.f-nav{  /* To fix main menu container */
    z-index: 9999;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
}
#main-menu-container {
    text-align: center; /* Assuming your main layout is centered */
}
#main-menu {
    display: inline-block;
    width: 1024px; /* Your menu's width */
}

JS

$("document").ready(function($){
    var nav = $('#main-menu-container');

    $(window).scroll(function () {
        if ($(this).scrollTop() > 125) {
            nav.addClass("f-nav");
        } else {
            nav.removeClass("f-nav");
        }
    });
});

【讨论】:

    【解决方案3】:

    与 adamb 相同,但我会添加一个动态变量 num

    num = $('.menuFlotante').offset().top;
    

    获取窗口内的确切偏移或位置以避免找到正确的位置。

     $(window).bind('scroll', function() {
             if ($(window).scrollTop() > num) {
                 $('.menu').addClass('fixed');
             }
             else {
                 num = $('.menuFlotante').offset().top;
                 $('.menu').removeClass('fixed');
             }
        });
    

    【讨论】:

    • 这很好,因为它避免了其他示例中发生的常见错误。 Chrome 有时会在 和第一个
      之间添加一个愚蠢而无意义的间隙,通常是那个
      的高度。谢谢。
    • +1 这是一个更好的解决方案!因为使用变量值来比较 .scrollTop(),如果您在不同设备(如 iPad 等)上浏览的网站在桌面浏览器的行为方式上有所不同,这将很有帮助。
    • @BornKillaz,可以应用css规则排序*:empty {display:none;}
    【解决方案4】:

    你也可以使用css规则:

    position: fixed ;top: 0px ;

    在您的菜单标签上。

    【讨论】:

    • 这是正确的做法。让 CSS 做它的设计。在 JQuery 中添加功能会给您的项目增加不必要的体积。
    • @PseudoNinja 是的,但是如果您查看 Wilson 提供的页面作为示例,菜单栏仅在用户滚动超过其相对位置时“固定”。这不能仅在 CSS 中实现。
    【解决方案5】:

    或者以更动态的方式执行此操作

    $(window).bind('scroll', function () {
        var menu = $('.menu');
        if ($(window).scrollTop() > menu.offset().top) {
            menu.addClass('fixed');
        } else {
            menu.removeClass('fixed');
        }
    });
    

    在 CSS 中添加类

    .fixed {
        position: fixed;
        top: 0;
    }
    

    【讨论】:

    • 需要&gt;= 而不是&gt; 否则菜单会在您滚动时跳进跳出。
    【解决方案6】:

    尝试使用粘性 jquery 插件

    https://github.com/garand/sticky

    <script src="jquery.js"></script>
    <script src="jquery.sticky.js"></script>
    <script>
      $(document).ready(function(){
        $("#sticker").sticky({topSpacing:0});
      });
    </script>

    【讨论】:

      【解决方案7】:

      您可能需要添加:

       $(window).trigger('scroll') 
      

      在您重新加载已经滚动的页面时触发滚动事件。否则你可能会让你的菜单错位。

      $(document).ready(function(){
              $(window).trigger('scroll');
              $(window).bind('scroll', function () {
                  var pixels = 600; //number of pixels before modifying styles
                  if ($(window).scrollTop() > pixels) {
                      $('header').addClass('fixed');
                  } else {
                      $('header').removeClass('fixed');
                  }
              }); 
      }); 
      

      【讨论】:

      • 重新加载时,浏览器自动滚动到最后一个位置,触发滚动事件,否则如果不自动滚动,则无需更改菜单位置。
      【解决方案8】:

      查看下面的链接,它有 html、css、JS 和现场演示 :) 享受

      http://codepen.io/senff/pen/ayGvD

      // Create a clone of the menu, right next to original.
      $('.menu').addClass('original').clone().insertAfter('.menu').addClass('cloned').css('position','fixed').css('top','0').css('margin-top','0').css('z-index','500').removeClass('original').hide();
      
      scrollIntervalID = setInterval(stickIt, 10);
      
      
      function stickIt() {
      
        var orgElementPos = $('.original').offset();
        orgElementTop = orgElementPos.top;               
      
        if ($(window).scrollTop() >= (orgElementTop)) {
          // scrolled past the original position; now only show the cloned, sticky element.
      
          // Cloned element should always have same left position and width as original element.     
          orgElement = $('.original');
          coordsOrgElement = orgElement.offset();
          leftOrgElement = coordsOrgElement.left;  
          widthOrgElement = orgElement.css('width');
      
          $('.cloned').css('left',leftOrgElement+'px').css('top',0).css('width',widthOrgElement+'px').show();
          $('.original').css('visibility','hidden');
        } else {
          // not scrolled past the menu; only show the original menu.
          $('.cloned').hide();
          $('.original').css('visibility','visible');
        }
      }
      * {font-family:arial; margin:0; padding:0;}
      .logo {font-size:40px; font-weight:bold;color:#00a; font-style:italic;}
      .intro {color:#777; font-style:italic; margin:10px 0;}
      .menu {background:#00a; color:#fff; height:40px; line-height:40px;letter-spacing:1px; width:100%;}
      .content {margin-top:10px;}
      .menu-padding {padding-top:40px;}
      .content {padding:10px;}
      .content p {margin-bottom:20px;}
      &lt;div class="intro"&gt;Some tagline goes here&lt;/div&gt;

      【讨论】:

      • 这看起来比它需要的复杂得多。
      【解决方案9】:

      这是 jquery 代码,用于在触摸浏览器顶部时修复 div,希望对您有很大帮助。

      <script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
      <script type='text/javascript'>//<![CDATA[ 
      $(window).load(function(){
      $(function() {
          $.fn.scrollBottom = function() {
              return $(document).height() - this.scrollTop() - this.height();
          };
      
          var $el = $('#sidebar>div');
          var $window = $(window);
          var top = $el.parent().position().top;
      
          $window.bind("scroll resize", function() {
              var gap = $window.height() - $el.height() - 10;
              var visibleFoot = 172 - $window.scrollBottom();
              var scrollTop = $window.scrollTop()
      
              if (scrollTop < top + 10) {
                  $el.css({
                      top: (top - scrollTop) + "px",
                      bottom: "auto"
                  });
              } else if (visibleFoot > gap) {
                  $el.css({
                      top: "auto",
                      bottom: visibleFoot + "px"
                  });
              } else {
                  $el.css({
                      top: 0,
                      bottom: "auto"
                  });
              }
          }).scroll();
      });
      });//]]>  
      
      </script>
      

      【讨论】:

        【解决方案10】:
        $(window).scroll(function () {
        
                var ControlDivTop = $('#cs_controlDivFix');
        
                $(window).scroll(function () {
                    if ($(this).scrollTop() > 50) {
                       ControlDivTop.stop().animate({ 'top': ($(this).scrollTop() - 62) + "px" }, 600);
                    } else {
                      ControlDivTop.stop().animate({ 'top': ($(this).scrollTop()) + "px" },600);
                    }
                });
            });
        

        【讨论】:

          【解决方案11】:

          你可以用你的导航试试这个div

          div.fixed{
              postion: fixed;
              top: 0;
              width: 100%;
          }
          

          【讨论】:

            【解决方案12】:

            使用 JavaScript,当某些元素进入或离开视口时,您可以使用 Intersection Observer API 触发此效果。

            https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

            【讨论】:

              猜你喜欢
              相关资源
              最近更新 更多
              热门标签