![](/img/trans.png)
[英]Why doesn't my nav bar hide when scrolling down and appear when scrolling up?
[英]JQUERY: why isn't my nav fixed to the top when scrolling down?
当您向下滚动页面100px时,我不会将导航栏固定在顶部。 然后向上滚动时返回到其正常状态。
我设法使导航栏在滚动时变得固定和不固定,但是滚动条不在正确的位置。 它将页面固定在页面的左侧和左侧,而不是页面顶部并浮动在右侧。
这是我在jsfiddle上制作的示例,供您查看。
<div id="wrapper">
<div id="codeback">
</div>
<div id="container">
<div class="nav">
</div>
<div id="wrap">
</div>
</div><!-- END OF CONTAINER -->
</div>
body{
background-color:black;
}
#wrapper{
width:100%;
height:inherit;
}
#codeback{
width:100%;
height:100%;
background-image:url('capture.jpg');
background-repeat: no-repeat;
position:fixed;
left:0px;
top:0px;
z-index:-1;
}
#container{
width:100%;
float:right;
}
.nav{
margin-top:100px;
width:80%;
height:50px;
float:right;
background-color:blue;
position:relative;
}
#wrap{
float:right;
width:80%;
height:1500px;
background-color:white;
}
$(window).scroll(function (e) {
$el = $('.nav');
if ($(this).scrollTop() > 100 && $el.css('position') != 'fixed') {
$('.nav').css({ 'position': 'fixed', 'top': '0'});
}
if ($(this).scrollTop() < 100 && $el.css('position') == 'fixed') {
$('.nav').css({ 'position': 'relative'});
}
});
您可以在课堂上轻松完成...
$(window).scroll(function (e) {
$el = $('.nav');
if ($(this).scrollTop() > 100) {
$('.nav').addClass("fixedNav");
}else {
$('.nav').removeClass("fixedNav");
}
});
.fixedNav {
position:fixed;
margin:0;
width:100%;
}
这里的小提琴: http : //jsfiddle.net/yss9hz0v/
因为.nav元素的margin-top: 100px;
在其CSS属性中...
小提琴: http : //jsfiddle.net/edL5F/24/
float:right
在位置fixed
时没有任何影响。 因此,当您将元素设置为fixed
位置时,必须设置right:0px
。
最后,每次将元素位置从“ fixed
更改为“ relative
分别为0px
和100px
时,都必须更改margin-top
尝试:
$(window).scroll(function (e) {
$el = $('.nav');
if ($(this).scrollTop() > 100 && $el.css('position') != 'fixed') {
$('.nav').css({ 'position': 'fixed', 'top': '0','right':'0','margin-top':'0px'});
}
if ($(this).scrollTop() < 100 && $el.css('position') == 'fixed') {
$('.nav').css({ 'position': 'relative','margin-top':'100px'});
}
});
这是我的解决方案:
margin-top
表格.nav
padding-top:100px
添加到#container
jQuery的:
$(window).scroll(function (e) {
$el = $('.nav');
if ($(this).scrollTop() > 100 && $el.css('position') != 'fixed') {
$('.nav').css({ 'position': 'fixed', 'top': '0','right':'0'});
}
if ($(this).scrollTop() < 100 && $el.css('position') == 'fixed') {
$('.nav').css({ 'position': 'relative','margin-top':'100px'});
}
});
这是一个小提琴 。
说明: right:0
是将.nav
固定后附加到右侧。
填充更改的边距是在向上滚动时强制条回到其原始位置,而无需编辑任何CSS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.