[英]Trying to make nav menu stick at top of screen when scrolling
滚动时,我正在使菜单停留在顶部。 我在这里跟随一个例子: https : //stackoverflow.com/a/1216130/571723
但是,我的菜单位于较小的居中div中。 当菜单转到顶部的“粘贴”时,菜单将推到页面的右侧。 这是我的小提琴: http : //jsfiddle.net/edL5F/1/
将菜单设置为固定状态时,如何使菜单停留在容器内?
CSS:
.content-wrapper {
margin: 0 auto;
max-width: 800px;
position: relative;
background-color: #cccccc;
}
nav {
position: absolute;
right: 0;
top: 63px;
margin-top: 5px;
font-size: 1.3em;
font-weight: 600;
list-style:none;
width:628px;
margin:5px auto;
height:43px;
padding:0px 10px 0px 10px;
z-index: 10;
/* Rounded Corners */
/*border-radius: 10px; */
/* Background color and gradients */
background: #014464;
background: -moz-linear-gradient(top, #0272a7, #013953);
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#0272a7), to(#013953));
/* Borders */
border: 1px solid #002232;
box-shadow: inset 0px 0px 1px #edf9ff;
}
div.divBlock {
margin: 20px 0;
}
JS:
$(window).scroll(function (e) {
$el = $('nav');
if ($(this).scrollTop() > 80 && $el.css('position') != 'fixed') {
$('nav').css({ 'position': 'fixed', 'top': '-10px'});
}
if ($(this).scrollTop() < 80 && $el.css('position') == 'fixed') {
$('nav').css({ 'position': 'absolute', 'top': '63px' });
}
});
您需要像这样将左:150,右:0放到函数中:
$(window).scroll(function (e) {
$el = $('nav');
if ($(this).scrollTop() > 80 && $el.css('position') != 'fixed') {
$('nav').css({ 'position': 'fixed', 'top': '-10px', 'left':'150px', 'right':'0'});
}
if ($(this).scrollTop() < 80 && $el.css('position') == 'fixed') {
$('nav').css({ 'position': 'absolute', 'top': '63px', 'left':'', 'right':'' });
}
});
这是工作的jsFiddle: http : //jsfiddle.net/k49n4/
问题是,当您添加position: fixed
到元素时,它将使元素脱离文档流。 它位于使它们保持浮动的所有其他元素之上。
您有right: 0
nav
样式为right: 0
。 只要绝对定位,它就会粘在其父对象的右侧。
当您将其更改为固定位置时,它也将粘贴在其父对象的右侧,在这种情况下就是视口。
您可以通过在固定状态下更改位置来修复它:
$('nav').css({
'position': 'fixed',
'top': '-10px',
'left': '50%',
'margin-left': '-250px' /* container width - image width */
});
还要检查此更新的Fiddle 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.