当向下滚动时如何建立浮动菜单栏

时间:2023-01-16 12:29:08

When I scrolled down site display black menu bar at the top look like float bar. but I think there's jquery involved with this. I have tried CSS but seems not working for me like the way i want it to

当我滚动网站显示黑色菜单栏在顶部看起来像浮动条。但我认为这与jquery有关。我尝试过CSS,但似乎不像我希望的那样

#menucontainer {
    position:fixed;
    top:0;
    height: 250px
}

#firstElement {
    margin-top: 250px
}

Here is the website basic idea of what I would like the menu to be like:

以下是我希望菜单是什么样子的基本想法:

http://avathemes.com/WP/Hexic/

http://avathemes.com/WP/Hexic/

5 个解决方案

#1


46  

Wrap your menu in an div or section with an ID or class.

用ID或类将菜单包装在div或section中。

#yourID.fixed {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1;
    width: 100%;
    border-bottom: 5px solid #ffffff;
}

//STICKY NAV
$(document).ready(function () {  
  var top = $('#yourID').offset().top - parseFloat($('#yourID').css('marginTop').replace(/auto/, 100));
  $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= top) {
      // if so, ad the fixed class
      $('#yourID').addClass('fixed');
    } else {
      // otherwise remove it
      $('#yourID').removeClass('fixed');
    }
  });
});

Can't remember where I got this from, so no salutations to me, but it worked for me.

不记得我是从哪儿弄来的,所以没有人向我致意,但对我很管用。

#2


3  

i think that use Twitter Bootstrap can help you.

我认为使用Twitter引导可以帮助你。

Look at Navbar in bootstrap and search for "Fixed to top"

查看bootstrap中的Navbar并搜索“固定到顶部”

Edit: If you want something like you post, combine with something like this Leave menu bar fixed on top when scrolled .

编辑:如果你想要像你发布的东西,结合像这样的离开菜单栏固定在顶部时滚动。

When the menu has top offset equals something add class ".navbar-fixed-top".

当菜单有顶部偏移量时,就等于添加了类“。navbar-固定顶”。

#3


3  

Try this

试试这个

CSS

* {margin: 0; padding: 0; outline: 0;}


body {
    font-family: Helvetica, Arial, Verdana, sans-serif;
    color: #999;
    font-size: 12px;
    background:#bfbfbf;


}


h1, h2 {
    font-family: 'Open Sans', sans-serif;
    font-weight: 300;
    margin:0 0 15px 0;
}


h1 {
    font-size: 36px;
    letter-spacing: -2px;
    line-height: 100%;
}

h1.title {
    font-size: 46px;
    font-weight: 700;
    color: #6a6a6a;


}


h2 {
    font-size: 24px;
}

p {
    margin: 0 0 15px 0;
}

.menuBtn {

    background: center center no-repeat transparent;
    background: #000;
    display: block;
    width: 40px;
    height: 40px;
    position: absolute;
    top: 0;
    left: 10px;

}

.clear {
    clear: both;
}
.wrap {
        /*background:url(../images/bg.png) top left repeat-x;*/
        width: 100%;
        max-width: 1140px;
        min-width: 960px;
        z-index: 10;
        position: relative;
        margin: 0 auto;
        padding: 0;

}



.section {
    width: 100%;
    max-width: 1140px;
    min-width: 960px;
    z-index: 10;
    position: relative;
    margin: 0 auto;
    padding: 0 0 20px 0;
}


.inner {
    width: 960px;
    margin: 0 auto;
    position: relative;
    min-height: 50px;
    padding:30px 0;
    font-size: 18px;
    font-family: 'Open Sans', sans-serif;
    font-weight: 300;
    padding:30px 0;
}


/* This is the selector i used for my menu, it needs to be set as position:absolute; */
.subMenu {
    position: absolute;
    top: 462px;
    height: 50px;
    z-index: 1000;
    width: 100%;
    max-width: 1140px;
    min-width: 960px;
    background: #aabd46;

}

.subMenu .inner {
    padding:0;
    font-weight: 400;
}





.subNavBtn {
    display: block;
    height: 35px;
    width: 12%;
    float: left;
    margin: 0px 0px 0 0;
    text-decoration: none;
    font-size: 14px;
    padding: 15px 2% 0 2%;
    text-align: center;
    color: #fff;
}

.end {
    margin: 0;
}


/* SECTIONS */
.sTop {
    min-height: 630px;
    background:#e5e5e5;
    color:#3d3d3d;

}



.s1 {
    min-height: 500px;
    background: #2e2e2e;
}


.s2 {
    min-height: 500px;
    background: #3f3f3f;
}


.s3 {
    min-height: 500px;
    background: #504f4f;
}


.s4 {
    min-height: 500px;
    background: #6e87a1;
    color: white;
}

.s5 {
    min-height: 500px;
    background: #293b4d;
    color: white;
}

JavaScript

:

:

  (function(){


        $.fn.smint = function( options ) {

            // adding a class to users div
            $(this).addClass('smint')

            var settings = $.extend({
                'scrollSpeed '  : 500
                }, options);


            return $('.smint a').each( function() {


                if ( settings.scrollSpeed ) {

                    var scrollSpeed = settings.scrollSpeed

                }


                ///////////////////////////////////

                // get initial top offset for the menu 
                var stickyTop = $('.smint').offset().top;   

                // check position and make sticky if needed
                var stickyMenu = function(){

                    // current distance top
                    var scrollTop = $(window).scrollTop(); 

                    // if we scroll more than the navigation, change its position to fixed and add class 'fxd', otherwise change it back to absolute and remove the class
                    if (scrollTop > stickyTop) { 
                        $('.smint').css({ 'position': 'fixed', 'top':0 }).addClass('fxd');

                        } else {
                            $('.smint').css({ 'position': 'absolute', 'top':stickyTop }).removeClass('fxd'); 
                        }   
                };

                // run function
                stickyMenu();

                // run function every time you scroll
                $(window).scroll(function() {
                     stickyMenu();
                });

                ///////////////////////////////////////


                $(this).on('click', function(e){


                    // gets the height of the users div. This is used for off-setting the scroll so th emenu doesnt overlap any content in the div they jst scrolled to
                    var selectorHeight = $('.smint').height();   

                    // stops empty hrefs making the page jump when clicked
                    e.preventDefault();

                    // get id pf the button you just clicked
                    var id = $(this).attr('id');

                    // gets the distance from top of the div class that matches your button id minus the height of the nav menu. This means the nav wont initially overlap the content.
                    var goTo =  $('div.'+ id).offset().top -selectorHeight;

                    // Scroll the page to the desired position!
                    $("html, body").animate({ scrollTop: goTo }, scrollSpeed);

                }); 



            });

        }

    })();

HTML

<!DOCTYPE html>
<html>
<head>
<title>SMINT Demo</title>

<meta name = "keywords" content = "" />
<meta name = "description" content = "" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, minimum-scale=1 user-scalable=no">

<link href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,700' rel='stylesheet' type='text/css'>

<link href="css/demo.css" rel="stylesheet" type="text/css">

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<script type="text/javascript"  src="js/jquery.smint.js"></script>

<script type="text/javascript">

$(document).ready( function() {
    $('.subMenu').smint({
        'scrollSpeed' : 1000
    });
});

</script>

</head>

<body>

    <div class="wrap">

      <div class="subMenu" >
        <div class="inner">
            <a href="#" id="sTop" class="subNavBtn">Home</a> 
            <a href="#" id="s1" class="subNavBtn">About me </a>
            <a href="#" id="s2" class="subNavBtn"> Portfolio</a>
            <a href="#" id="s3" class="subNavBtn">Working</a>
            <a href="#" id="s4" class="subNavBtn">Hello</a>
            <a href="#" id="s5" class="subNavBtn end">lets go</a>
        </div>



    </div>


    <div class="section sTop">



        <div class="inner">
            <h1>Welcome to my site </h1>
            <p>Click the links below !</p>

        </div>
        <br class="clear">
    </div>





    <div class="section s1">

        <div class="inner">

            <h1>About me </h1>

        </div>

    </div>

    <div class="section s2">
        <div class="inner">

            <h1>Portfolio</h1>

        </div>

    </div>

    <div class="section s3">
        <div class="inner">

        <h1>Working Standards</h1>

        </div>

    </div>

    <div class="section s4">
        <div class="inner">

            <h1>Hello</h1>

        </div>

    </div>

    <div class="section s5">
        <div class="inner">

        <h1>Lets Go</h1>

        </div>

    </div>



</div>
</body>
</html>

#4


2  

I tried many times for the solution @Kortschot provided, while finally it turned out to be that this solution wasn't ideal for my situation.

我尝试了很多次@Kortschot提供的解决方案,但最终结果是这个解决方案并不适合我的情况。

Here is my problem when using the solution @Kortschot provided :

以下是我在使用@Kortschot提供的解决方案时遇到的问题:

  • The width of floating bar can not maintain when floating bar's states change between fix or not fix
  • 当浮动条的状态在固定或不固定之间发生变化时,浮动条的宽度不能保持
  • I want all the process can be done in just one script, while the solution @Kortschot provided doesn't fit.
  • 我希望所有的过程都可以在一个脚本中完成,而@Kortschot提供的解决方案并不适用。

Here is my solution which can do all the work in just one script (using 1.7+ jquery):

下面是我的解决方案,它可以只用一个脚本(使用1.7+ jquery)完成所有的工作:

<script>
//浮动条设置(set the floating bar)
$( function(){
    //add new .fixed style to the <head>
    var css = '#floating_bar.fixed{position:fixed;top:1px;z-index:9999;}',
        head = document.head || document.getElementsByTagName('head')[0],
        style = document.createElement('style');
    style.type = 'text/css';
    if (style.styleSheet){ style.styleSheet.cssText = css; } 
    else { style.appendChild(document.createTextNode(css)); }
    head.appendChild(style);

    var menuOffset = $("#floating_bar")[0].offsetTop;
    var menuWidth = document.getElementById("floating_bar").offsetWidth;
    $(document).on("scroll", function(){
        var docScroll = $(document).scrollTop();
        if(docScroll >= menuOffset) { 
            $("#floating_bar").addClass("fixed");
            //dynamically change the width of floating bar according to it's width of previous state 
            $("#floating_bar.fixed").width(menuWidth);
        }else {
            $("#floating_bar").removeClass("fixed");
        }
    });
});
</script> 

#5


0  

In the URL that you provide, I see a menu bar fixed on the top of browser while you scroll down several lines of the page.

在您提供的URL中,我看到一个固定在浏览器顶部的菜单栏,您向下滚动页面的几行。

So I separate your problem to 2 questions: First, how to make a fixed top menu which won't be disappear when scroll the page. Second, how to make a menu fixed on top after scrolling down few lines.

所以我把你的问题分为两个问题:第一,如何制作一个固定的顶部菜单,当你滚动页面时不会消失。第二,在向下滚动几行之后,如何将菜单固定在上面。

For the first question, I change your css code.

对于第一个问题,我更改了您的css代码。

#menucontainer {
    float:top;
    position:fixed;
    top:0;
    height: 100px;
    width: 100%;
    background-color: eeee00; /* makes other content won't be seen when the page scrolling */
}

And I think the second question need to write js. Well I don't know yet.

我认为第二个问题需要写js。我还不知道。

#1


46  

Wrap your menu in an div or section with an ID or class.

用ID或类将菜单包装在div或section中。

#yourID.fixed {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1;
    width: 100%;
    border-bottom: 5px solid #ffffff;
}

//STICKY NAV
$(document).ready(function () {  
  var top = $('#yourID').offset().top - parseFloat($('#yourID').css('marginTop').replace(/auto/, 100));
  $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= top) {
      // if so, ad the fixed class
      $('#yourID').addClass('fixed');
    } else {
      // otherwise remove it
      $('#yourID').removeClass('fixed');
    }
  });
});

Can't remember where I got this from, so no salutations to me, but it worked for me.

不记得我是从哪儿弄来的,所以没有人向我致意,但对我很管用。

#2


3  

i think that use Twitter Bootstrap can help you.

我认为使用Twitter引导可以帮助你。

Look at Navbar in bootstrap and search for "Fixed to top"

查看bootstrap中的Navbar并搜索“固定到顶部”

Edit: If you want something like you post, combine with something like this Leave menu bar fixed on top when scrolled .

编辑:如果你想要像你发布的东西,结合像这样的离开菜单栏固定在顶部时滚动。

When the menu has top offset equals something add class ".navbar-fixed-top".

当菜单有顶部偏移量时,就等于添加了类“。navbar-固定顶”。

#3


3  

Try this

试试这个

CSS

* {margin: 0; padding: 0; outline: 0;}


body {
    font-family: Helvetica, Arial, Verdana, sans-serif;
    color: #999;
    font-size: 12px;
    background:#bfbfbf;


}


h1, h2 {
    font-family: 'Open Sans', sans-serif;
    font-weight: 300;
    margin:0 0 15px 0;
}


h1 {
    font-size: 36px;
    letter-spacing: -2px;
    line-height: 100%;
}

h1.title {
    font-size: 46px;
    font-weight: 700;
    color: #6a6a6a;


}


h2 {
    font-size: 24px;
}

p {
    margin: 0 0 15px 0;
}

.menuBtn {

    background: center center no-repeat transparent;
    background: #000;
    display: block;
    width: 40px;
    height: 40px;
    position: absolute;
    top: 0;
    left: 10px;

}

.clear {
    clear: both;
}
.wrap {
        /*background:url(../images/bg.png) top left repeat-x;*/
        width: 100%;
        max-width: 1140px;
        min-width: 960px;
        z-index: 10;
        position: relative;
        margin: 0 auto;
        padding: 0;

}



.section {
    width: 100%;
    max-width: 1140px;
    min-width: 960px;
    z-index: 10;
    position: relative;
    margin: 0 auto;
    padding: 0 0 20px 0;
}


.inner {
    width: 960px;
    margin: 0 auto;
    position: relative;
    min-height: 50px;
    padding:30px 0;
    font-size: 18px;
    font-family: 'Open Sans', sans-serif;
    font-weight: 300;
    padding:30px 0;
}


/* This is the selector i used for my menu, it needs to be set as position:absolute; */
.subMenu {
    position: absolute;
    top: 462px;
    height: 50px;
    z-index: 1000;
    width: 100%;
    max-width: 1140px;
    min-width: 960px;
    background: #aabd46;

}

.subMenu .inner {
    padding:0;
    font-weight: 400;
}





.subNavBtn {
    display: block;
    height: 35px;
    width: 12%;
    float: left;
    margin: 0px 0px 0 0;
    text-decoration: none;
    font-size: 14px;
    padding: 15px 2% 0 2%;
    text-align: center;
    color: #fff;
}

.end {
    margin: 0;
}


/* SECTIONS */
.sTop {
    min-height: 630px;
    background:#e5e5e5;
    color:#3d3d3d;

}



.s1 {
    min-height: 500px;
    background: #2e2e2e;
}


.s2 {
    min-height: 500px;
    background: #3f3f3f;
}


.s3 {
    min-height: 500px;
    background: #504f4f;
}


.s4 {
    min-height: 500px;
    background: #6e87a1;
    color: white;
}

.s5 {
    min-height: 500px;
    background: #293b4d;
    color: white;
}

JavaScript

:

:

  (function(){


        $.fn.smint = function( options ) {

            // adding a class to users div
            $(this).addClass('smint')

            var settings = $.extend({
                'scrollSpeed '  : 500
                }, options);


            return $('.smint a').each( function() {


                if ( settings.scrollSpeed ) {

                    var scrollSpeed = settings.scrollSpeed

                }


                ///////////////////////////////////

                // get initial top offset for the menu 
                var stickyTop = $('.smint').offset().top;   

                // check position and make sticky if needed
                var stickyMenu = function(){

                    // current distance top
                    var scrollTop = $(window).scrollTop(); 

                    // if we scroll more than the navigation, change its position to fixed and add class 'fxd', otherwise change it back to absolute and remove the class
                    if (scrollTop > stickyTop) { 
                        $('.smint').css({ 'position': 'fixed', 'top':0 }).addClass('fxd');

                        } else {
                            $('.smint').css({ 'position': 'absolute', 'top':stickyTop }).removeClass('fxd'); 
                        }   
                };

                // run function
                stickyMenu();

                // run function every time you scroll
                $(window).scroll(function() {
                     stickyMenu();
                });

                ///////////////////////////////////////


                $(this).on('click', function(e){


                    // gets the height of the users div. This is used for off-setting the scroll so th emenu doesnt overlap any content in the div they jst scrolled to
                    var selectorHeight = $('.smint').height();   

                    // stops empty hrefs making the page jump when clicked
                    e.preventDefault();

                    // get id pf the button you just clicked
                    var id = $(this).attr('id');

                    // gets the distance from top of the div class that matches your button id minus the height of the nav menu. This means the nav wont initially overlap the content.
                    var goTo =  $('div.'+ id).offset().top -selectorHeight;

                    // Scroll the page to the desired position!
                    $("html, body").animate({ scrollTop: goTo }, scrollSpeed);

                }); 



            });

        }

    })();

HTML

<!DOCTYPE html>
<html>
<head>
<title>SMINT Demo</title>

<meta name = "keywords" content = "" />
<meta name = "description" content = "" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, minimum-scale=1 user-scalable=no">

<link href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,700' rel='stylesheet' type='text/css'>

<link href="css/demo.css" rel="stylesheet" type="text/css">

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<script type="text/javascript"  src="js/jquery.smint.js"></script>

<script type="text/javascript">

$(document).ready( function() {
    $('.subMenu').smint({
        'scrollSpeed' : 1000
    });
});

</script>

</head>

<body>

    <div class="wrap">

      <div class="subMenu" >
        <div class="inner">
            <a href="#" id="sTop" class="subNavBtn">Home</a> 
            <a href="#" id="s1" class="subNavBtn">About me </a>
            <a href="#" id="s2" class="subNavBtn"> Portfolio</a>
            <a href="#" id="s3" class="subNavBtn">Working</a>
            <a href="#" id="s4" class="subNavBtn">Hello</a>
            <a href="#" id="s5" class="subNavBtn end">lets go</a>
        </div>



    </div>


    <div class="section sTop">



        <div class="inner">
            <h1>Welcome to my site </h1>
            <p>Click the links below !</p>

        </div>
        <br class="clear">
    </div>





    <div class="section s1">

        <div class="inner">

            <h1>About me </h1>

        </div>

    </div>

    <div class="section s2">
        <div class="inner">

            <h1>Portfolio</h1>

        </div>

    </div>

    <div class="section s3">
        <div class="inner">

        <h1>Working Standards</h1>

        </div>

    </div>

    <div class="section s4">
        <div class="inner">

            <h1>Hello</h1>

        </div>

    </div>

    <div class="section s5">
        <div class="inner">

        <h1>Lets Go</h1>

        </div>

    </div>



</div>
</body>
</html>

#4


2  

I tried many times for the solution @Kortschot provided, while finally it turned out to be that this solution wasn't ideal for my situation.

我尝试了很多次@Kortschot提供的解决方案,但最终结果是这个解决方案并不适合我的情况。

Here is my problem when using the solution @Kortschot provided :

以下是我在使用@Kortschot提供的解决方案时遇到的问题:

  • The width of floating bar can not maintain when floating bar's states change between fix or not fix
  • 当浮动条的状态在固定或不固定之间发生变化时,浮动条的宽度不能保持
  • I want all the process can be done in just one script, while the solution @Kortschot provided doesn't fit.
  • 我希望所有的过程都可以在一个脚本中完成,而@Kortschot提供的解决方案并不适用。

Here is my solution which can do all the work in just one script (using 1.7+ jquery):

下面是我的解决方案,它可以只用一个脚本(使用1.7+ jquery)完成所有的工作:

<script>
//浮动条设置(set the floating bar)
$( function(){
    //add new .fixed style to the <head>
    var css = '#floating_bar.fixed{position:fixed;top:1px;z-index:9999;}',
        head = document.head || document.getElementsByTagName('head')[0],
        style = document.createElement('style');
    style.type = 'text/css';
    if (style.styleSheet){ style.styleSheet.cssText = css; } 
    else { style.appendChild(document.createTextNode(css)); }
    head.appendChild(style);

    var menuOffset = $("#floating_bar")[0].offsetTop;
    var menuWidth = document.getElementById("floating_bar").offsetWidth;
    $(document).on("scroll", function(){
        var docScroll = $(document).scrollTop();
        if(docScroll >= menuOffset) { 
            $("#floating_bar").addClass("fixed");
            //dynamically change the width of floating bar according to it's width of previous state 
            $("#floating_bar.fixed").width(menuWidth);
        }else {
            $("#floating_bar").removeClass("fixed");
        }
    });
});
</script> 

#5


0  

In the URL that you provide, I see a menu bar fixed on the top of browser while you scroll down several lines of the page.

在您提供的URL中,我看到一个固定在浏览器顶部的菜单栏,您向下滚动页面的几行。

So I separate your problem to 2 questions: First, how to make a fixed top menu which won't be disappear when scroll the page. Second, how to make a menu fixed on top after scrolling down few lines.

所以我把你的问题分为两个问题:第一,如何制作一个固定的顶部菜单,当你滚动页面时不会消失。第二,在向下滚动几行之后,如何将菜单固定在上面。

For the first question, I change your css code.

对于第一个问题,我更改了您的css代码。

#menucontainer {
    float:top;
    position:fixed;
    top:0;
    height: 100px;
    width: 100%;
    background-color: eeee00; /* makes other content won't be seen when the page scrolling */
}

And I think the second question need to write js. Well I don't know yet.

我认为第二个问题需要写js。我还不知道。