我正在尝试创建一个布局,其中 Logo 下方有一个水平菜单,当用户滚动经过 Logo 时,菜单固定在顶部。
$(window).scroll(function(e) {
$el = $('#menu');
if ($(this).scrollTop() > 100 && $el.css('position') != 'fixed') {
$('#menu').css({'position': 'fixed', 'top': '0px'});
$('#content-text').css({'margin-top': '50px'});
}
if ($(this).scrollTop() < 100 && $el.css('position') == 'fixed') {
$('#menu').css({'position': 'static', 'top': '100px'});
$('#content-text').css({'margin-top': '0px'});
}
});
这样做我还必须更改主要内容的 margin-top
,否则它会跳转。
例子:
虽然固定菜单似乎有效,但当我更改内容部分的边距时,它现在与页面底部的页脚重叠。我该如何解决这个问题?
最佳答案
我会这样做。 OR - 以下两种方式之一。如果您确定知道高度,则可以添加和删除类。如果你不这样做,你可以查询它们。这是 a jsFiddle.
我认为真正的问题是 FF 是严格的,你的主要 block 并不是真正有组织的盒子模型明智的。如果你将它们全部向左浮动并使它们的宽度为 100% 等,它们将很好地堆叠。整个表格单元格的东西很糟糕。 float 的一致性会更好。
HTML
<header>
header
</header>
<nav>
<ul class="menu">
<li><a href="#">item</a></li>
<li><a href="#">item</a></li>
<li><a href="#">item</a></li>
</ul>
</nav>
<section>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Modi id dicta asperiores placeat tempore doloribus eius consequuntur vero libero fugiat quidem officia. Quae est temporibus non ad reiciendis excepturi doloribus!</p>
<ul>
<li>to show scroll</li>
<li>etc.</li>
</ul>
</section>
CSS
* {
box-sizing: border-box;
}
header, nav, section {
width: 100%;
float: left;
}
body {
margin: 0;
}
header {
background: red;
min-height: 100px;
}
nav {
background: lightblue;
}
.menu {
list-style: none;
margin: 0;
padding: 0;
}
section {
background: orange;
min-height: 1200px
}
.fixed-header nav {
position: fixed;
top: 0;
left: 0;
}
.fixed-header section {
background: lime;
/* you could set margin here, if you know the nav height for sure */
}
j查询
$(window).on('scroll', function() {
var navHeight = $('nav').outerHeight();
var headerHeight = $('header').outerHeight();
if ( $(this).scrollTop() > headerHeight ) {
$('body').addClass('fixed-header');
$('section').css({
'margin-top' : navHeight
});
} else if ( $(this).scrollTop() <= headerHeight ) {
$('body').removeClass('fixed-header');
$('section').css({
'margin-top' : 0
});
}
});
关于jquery - 滚动上的固定元素有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24961574/