简体   繁体   English

滚动时固定水平导航菜单

[英]fixed horizontal navigation menu upon scroll

I'm still relatively new to the world of programming and I am currently attempting to create a website with a horizontal navigation menu that sticks to the top of the page when scrolled down. 我还是相对较新的编程世界,我目前正在尝试创建一个带有水平导航菜单的网站,该菜单在向下滚动时会粘在页面顶部。 For example I want to create something such as the menu on http://www.w3schools.com/html/ The menu is a list inside a div which itself inside another div. 例如,我想创建一些东西,如http://www.w3schools.com/html/上的菜单。菜单是div内的一个列表,它本身位于另一个div中。 I tried to change the style of the enclosing div to fixed when the page is scrolled down with some javascript but this is very glitchy and doesn't work effectively. 当用一些javascript向下滚动页面时,我试图将封闭div的样式更改为固定,但这非常小问题并且无法有效工作。 Is there any other way I can do this? 有没有其他方法可以做到这一点?

This is the Javascript I am using at the bottom of the html file and the css just changes to position : fixed; 这是我在html文件底部使用的Javascript,而css只是更改为position : fixed;

<script type="text/javascript">
var header = $("#menu-wrapper");
var headerY = header.offset().top;
$(document).scroll(function () {
var y = $(document).scrollTop();

if (y >= headerY) {
    header.addClass('fixed');
} else {
    header.removeClass('fixed');
}
});`
</script>

The required view can be achieved using simple CSS3 , no need of JavaScript at initial level ! 使用简单的CSS3可以实现所需的视图,初始级别不需要JavaScript

Working Demo 工作演示

CSS code : CSS代码:

#cssmenu {
   position:fixed;
   top: 0;
   margin:auto;
   left: 0;
   right: 0;
   width: 100%;
   height: 50px;
   background-color: #4861A3;
}
$(document).ready(function() {
    $(window).scroll(function () {
       var scroll = $(this).scrollTop();
       var topDist = $("your container Selector").position();
       if (scroll > topDist.top) {
          $('Your Menu Seloctor').css({"position":"fixed","top":"0"});
       } else {
          $('Your Menu Seloctor').css({"position":"static","top":"auto"});
       }
   });

}); });

Above code working for fixed Menu on Scroll using Jquery. 上面的代码使用Jquery为Scroll上的固定Menu工作。 This code working even if your Navigation in middle of the page. 即使您的导航位于页面中间,此代码也能正常工作。

The question requires to give a little use of JQuery to get the desired output and also contains different Design style! 这个问题需要稍微使用JQuery来获得所需的输出,并且还包含不同的设计风格! hence adding another Answer! 因此添加另一个答案!

Here is working Demo 这是工作演示

JQuery Code : JQuery代码:

$("document").ready(function(){

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

    });

Important CSS : 重要的CSS:

.f-nav{ z-index: 9999; position: fixed; top: 0; width: 100%;} /* this make our menu float top */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM