滚动时将菜单栏固定在顶部


72

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

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

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

能否请您引导我到可以找到摘要的位置,以便我可以学习做类似的事情。


Answers:


158

这种效果通常是通过具有以下jquery逻辑来实现的:

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

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

有关完整的实施详细信息,请参见:http : //jsfiddle.net/adamb/F4BmP/


10
您不能通过执行以下操作来缩短此时间$('.menu').toggleClass('fixed', $(window).scrollTop() > 50);吗?
Michael J. Calkins 2014年

3
@MichaelCalkins是的(另一个是:),$('.menu')[($(window).scrollTop() > num ? 'add' : 'remove') + 'Class']('fixed');但是我认为它的编写方式可以最大程度地提高可读性。
adamb 2014年

1
对于IE,您可能需要添加z-index:1;.fixed以确保菜单位于顶部。
Ivan Chau

1
不幸的是,此实现将触发用户在if语句中放置的任何功能/交互,每次用户每次滚动一键单击6次,每次单击滚动条箭头向上或向下单击9次。此处针对多个事件的可能解决方案:stackoverflow.com/questions/9613594/…–
JPeG

1
toggleClass()缩短了代码,但在类之间切换时却产生了怪异的闪烁。
阿基尔

20

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

的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");
        }
    });
});

15

与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');
         }
    });

2
这很好,因为它避免了其他示例中常见的错误。Chrome有时会在<body>和第一个<div>之间添加一个愚蠢的废话间隙,通常带有该<div>的高度。谢谢。
BornKillaz 2015年

+1这是一个更好的解决方案!因为使用可变值比较.scrollTop(),如果您在不同的设备(如iPad等)中浏览站点,而这些设备的桌面浏览器的行为方式有所不同,则此方法将非常有用。
Irfan,2015年

@BornKillaz,可以通过应用CSS规则对它进行排序*:empty {display:none;}
stormec56

14

您还可以使用CSS规则:

position: fixed ;top: 0px ;

在您的菜单标签上。


6
这是正确的方法。让CSS做它打算做的事情。在JQuery中添加功能会为您的项目添加不必要的批量。
PseudoNinja

10
@PseudoNinja是的,但是如果您以Wilson提供的页面为例,则仅当用户滚动超过其相对位置时,菜单栏才“固定”。单靠CSS不能做到这一点。
adamb 2012年

6

或者以更动态的方式进行

$(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;
}

3
需要>=代替,>否则在滚动时菜单将在固定之间跳入和跳出。
杰克·威尔逊

3

您可能要添加:

 $(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');
            }
        }); 
}); 

重新加载时,浏览器会自动滚动到其最后一个位置,从而触发滚动事件,否则,如果它不自动滚动,则无需更改菜单的位置。
其他

3

检查下面的链接,它具有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;}
<div class="intro">Some tagline goes here</div>


2
这看起来比需要的复杂得多。
杰克·威尔逊

3

尝试使用粘性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>


2

这是jquery代码,用于在div接触浏览器顶部时修复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>

1

您可以用nav尝试一下div

postion: fixed;
top: 0;
width: 100%;

1
$(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);
            }
        });
    });
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.