将导航栏粘贴到页面顶部后,它从中间到最左侧

Upon sticking navbar to top of page, it goes from the middle to the very left

本文关键字:中间 顶部 导航      更新时间:2023-09-26

所以我目前正在做一个项目,并且有正确的代码在滚动通过后将菜单栏粘在顶部。但是,当菜单栏不是页面的 100% 时,它会向左压缩。有人知道如何把它放回原来的位置吗?

网页代码:

<div class="menucontainer">
    <ul class="menu">
        <li><a href="Default.aspx">Home</a></li>
        <li><a href="History.aspx">History</a></li>
        <li><a href="Gallery.aspx">Gallery</a></li>
        <li><a href="Services.aspx">Services</a></li>
        <li><a href="Contact.aspx">Contact</a></li>
    </ul>
</div>
<div id="stickyalias"></div>

j查询代码:

    $(function () {
        // Check the initial Poistion of the Sticky Header
        var stickyHeaderTop = $('.menucontainer').offset().top;
        $(window).scroll(function () {
            if ($(window).scrollTop() > stickyHeaderTop) {
                $('.menucontainer').css({ position: 'fixed', top: '0px' });
                $('#stickyalias').css('display', 'block');
            } else {
                $('.menucontainer').css({ position: 'static', top: '0px' });
                $('#stickyalias').css('display', 'none');
            }
        });
    });

一些CSS代码:

.menucontainer {
    height: 50px;
    line-height: 50px;
    clear: both;
    z-index: 9999;
    opacity: .9;
    margin-left: auto;
    margin-right: auto;
    width: 1100px;
    }

如果它对任何人有帮助,可以在 mor.actiongymok.com 访问该页面以查看其运行的实时版本。

这是固定元素的预期行为...如果尚未指定left值,则默认为 left:0; 。所以要居中,给它:

  left: 50%;
  margin-left: -550px; // half the width of your header

您必须根据需要跨断点调整此设置,但这就是您的导航像那样跳过的原因。

我认为您的菜单具有固定宽度。当菜单粘在顶部时,将类 .menucontainer 的宽度更改为 100%。

如果您希望菜单保持相同的大小,请将以下 CSS 添加到您的 .menucontainer 中

  .menucontainer{
   left: 0;
   right: 0;
   }
$(function () {
    // Check the initial Poistion of the Sticky Header
    var stickyHeaderTop = $('.menucontainer').offset().top;
    var menuContainerWidth =$('.menucontainer').outerWidth();
    $(window).scroll(function () {
        if ($(window).scrollTop() > stickyHeaderTop) {
            $('.menucontainer').css({ position: 'fixed', top: '0px',left:'50%',marginLeft:menuContainerWidth/2 + 'px'});
            $('#stickyalias').css('display', 'block');
        } else {
            $('.menucontainer').css({ position: 'static', top: '0px',left:'auto',marginLeft:'0px' });
            $('#stickyalias').css('display', 'none');
        }
    });
});

我建议使用bootstrap3。它应该内置到Visual Studio中。它使使用他们预先构建的 css 变得更加容易。