[英]How can I stop the bootstrap 4 navbar from sticking to the top of the page when in mobile viewport?
[英]Upon sticking navbar to top of page, it goes from the middle to the very left
因此,我目前正在研究一个项目,并且具有正确的代码,以便在滚动通过后将菜单栏粘贴到顶部。 但是,当菜单栏不是页面的100%时,它将向左移动。 有人知道如何将其放回原处吗?
HTML代码:
<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>
jQuery代码:
$(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
您必须根据需要在断点之间进行调整,这就是为什么您的导航像这样跳过的原因。
$(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');
}
});
});
我认为您的菜单宽度固定。 当菜单停留在顶部时,将class .menucontainer的宽度更改为100%。
如果您希望菜单保持相同大小,请将以下CSS添加到.menucontainer
.menucontainer{
left: 0;
right: 0;
}
我建议使用bootstrap3。 它应该内置在Visual Studio中。 使用他们的预构建CSS可以轻松得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.