如何将导航固定到滚动中心?
How fixed a navigation to the center on scroll?
我有一个以 80% 宽度居中的导航,当我滚动页面时,在某个时间点我将 header 固定到顶部,当我这样做时它浮动到左侧而不是留在中间。如何让导航居中固定在顶部
html
<div id="foo">
</div>
<div id="nav">
</div>
<div id="bar">
</div>
css
#foo{
height:100px;
width:100%;
}
#bar{
height:1000px;
width:100%;
}
#nav{
width: 80%;
height: 100px;
margin: 0 auto;
background-color: #FFCC00;
}
.fixed-nav{
position: fixed;
top: 0;
}
脚本
var bottom = $('#nav').offset().top;
$(window).scroll(function(){
if ($(this).scrollTop() > bottom){
$('#nav').addClass('fixed-nav');
}
else{
$('#nav').removeClass('fixed-nav');
}
});
这是我在 jsfiddle
中的代码
我有一个以 80% 宽度居中的导航,当我滚动页面时,在某个时间点我将 header 固定到顶部,当我这样做时它浮动到左侧而不是留在中间。如何让导航居中固定在顶部
html
<div id="foo">
</div>
<div id="nav">
</div>
<div id="bar">
</div>
css
#foo{
height:100px;
width:100%;
}
#bar{
height:1000px;
width:100%;
}
#nav{
width: 80%;
height: 100px;
margin: 0 auto;
background-color: #FFCC00;
}
.fixed-nav{
position: fixed;
top: 0;
}
脚本
var bottom = $('#nav').offset().top;
$(window).scroll(function(){
if ($(this).scrollTop() > bottom){
$('#nav').addClass('fixed-nav');
}
else{
$('#nav').removeClass('fixed-nav');
}
});
这是我在 jsfiddle
中的代码