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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13274592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:27:25  来源:igfitidea点击:

Leave menu bar fixed on top when scrolled

jquerycss

提问by Wilson

I've seen some websites that when the user scrolls down the page a box would pop-up to the right or left...

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

Also, noticed this template: http://www.mvpthemes.com/maxmag/the designer does a nice job leaving the nav bar fixed on top.

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

Now, how are these done? I guess it uses jquery to get the position of the page and to show the box.

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

Can you please guide me to where I can find a snippet so I can learn to do something like that.

能否请您指导我到哪里可以找到片段,以便我可以学习做类似的事情。

回答by adamb

This effect is typically achieved by having some jquery logic as follows:

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

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

This says once the window has scrolled past a certain number of vertical pixels, it adds a class to the menu that changes it's position value to "fixed".

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

For complete implementation details see: http://jsfiddle.net/adamb/F4BmP/

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

回答by Tomas Gonzalez

In this example, you may show your menu centered.

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

HTML

HTML

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

CSS

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

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

回答by mariosm

same as adamb but I would add a dynamic variable num

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

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

to get the exact offset or position inside the window to avoid finding the right position.

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

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

回答by LGreen

You can also use css rules:

您还可以使用 css 规则:

position: fixed ;and top: 0px ;

position: fixed ;top: 0px ;

on your menu tag.

在您的菜单标签上。

回答by Bilal Iqbal

Or do this in more dynamic way

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

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

In CSS add class

在 CSS 添加类

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

回答by Thoman

try with sticky jquery plugin

尝试使用粘性 jquery 插件

https://github.com/garand/sticky

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>

回答by Athmane

you may want to add:

您可能想要添加:

 $(window).trigger('scroll') 

to trigger the scroll event when you reload an already scrolled page. Otherwise you might get your menu out of position.

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

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

回答by Athmane

check the link below, it has the html, css, JS and a live demo :) enjoy

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

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

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>

回答by manzoor

This is jquery code which is used to fixed the div when it touch a top of browser hope it will help a lot.

这是 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>

回答by Sumit patel

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