简体   繁体   English

垂直固定的导航栏

[英]Vertically fixed navigation bar

I would like to create vertically a fixed navigation bar for my site. 我想为我的网站垂直创建一个固定的导航栏。 Currently i use the one that has been mentioned on various posts here: 目前,我使用这里各种帖子中提到的内容:

HTML: HTML:

<html>
<head>
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="{% static 'navbar.css' %}">   

    <script type="application/javascript">
        $(document).ready(function () {
            var navPos = $('.nav_menu').offset().top; //Sticky navbar
            $(window).scroll(function () {
                var scrollPos = $(this).scrollTop();
                if (scrollPos >= navPos) {
                    $('.nav_menu').addClass('fixed');
                } else {
                    $('.nav_menu').removeClass('fixed');
                }
            });
        });
    </script>
    .....
    <div class="nav-container">
        <div class="nav_menu">
            Bars go here
    ....

And CSS: 和CSS:

.nav-container .nav_menu.fixed {position: fixed; z-index: 10000; top: 0; width: 195px; padding-left: 8px}

This solution works great, the navbar is sticked, in my case the navbar is on the top left side of the page. 此解决方案效果很好,导航栏已粘贴,在我的情况下,导航栏位于页面的左上方。 If i scroll down it perfectly follows the scroll. 如果我向下滚动,则完全跟随滚动。 In case i open the gape using a small window and i stoll down plus right the bar follows (as it should happen). 万一我用一个小窗户打开缝隙,然后我往下拉起,右边的杠就会跟着走(这应该发生)。 However i would like the bar to only follow vertically, in case someone scrolls left or right the bar should stay where it is. 但是,我希望该条仅垂直跟随,以防有人向左或向右滚动,该条应保持在原位。

How can i achieve this? 我怎样才能做到这一点?

You can stop the horizontal fixed by applying minus left scroll: 您可以通过应用负向左滚动来停止水平固定:

 var $window = $(window); var navPos = $('.nav_menu').offset().top; //Sticky navbar $window.scroll(function() { var scrollPos = $window.scrollTop(); var left = 0 - $window.scrollLeft(); if (scrollPos >= navPos) { $('.nav_menu').addClass('fixed').css('left', left + 'px'); } else { $('.nav_menu').removeClass('fixed').css('left', 0); } }); 
 body, html { height: 1000px; width: 2000px; position: relative; margin: 0; padding: 0; } .nav_menu { height: 50px; background-color: blue; width: 195px; } .fixed { position: fixed; top: 0; left: 0; z-index: 2; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <br><br><br> <div class="nav_menu"></div> 

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

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