我正在尝试创建一个固定的导航栏,它会向下滚动并在向上滚动时显示备份。
我的导航栏位于距离顶部37.5像素处,当我向上滚动时,如果我在页面中间,我希望它位于页面顶部。
这是我尝试过的。
CSS
.nav-up
top -80px
background-color #8fd0f3
.nav-down
top 0
.navbar-wrapper
position fixed
// top -7px
top 37.5px
// -webkit-transform translateY(37.5px)
z-index 100
width 100%
padding-top 17.5px
transition top 0.2s ease-in-out
padding-bottom 17.5px
.navbar-elements
width 960px
margin 0 auto
position relative
.logo
cursor pointer
.nav-buttons
text-transform uppercase
position absolute
right 0
top 0
display inline-block
.nav-btn
display inline-block
vertical-align middle
border-radius 4px
padding 12px 21px 12px 21px
font-family 'Lato'
cursor pointer
// transition opacity 0.3s ease
.breeder-btn
background-color rgba(255, 255, 255, 1)
margin-left 10px
transition background-color 0.2s ease
// margin-right 136px
.breeder-btn:hover
background-color rgba(255, 255, 255, 0.85)
.guarantee-btn
background-color rgba(17, 35, 114, 1)
color white
transition background-color 0.2s ease
.guarantee-btn:hover
background-color rgba(17,35,114, 0.85)
HTML
<div class="navbar-wrapper nav-down">
<div class="navbar-elements">
<img src="../img/logo.png" class="logo">
<div class="nav-buttons">
<div class="nav-btn guarantee-btn">
our guarantee
</div>
<div class="nav-btn breeder-btn">
new breeder sign-up
</div>
</div>
</div>
</div>
JS
// Hide Header on on scroll
function HeaderScroll() {
var delta = 5;
var navbarHeight = $('.navbar-wrapper').outerHeight();
console.log(navbarHeight);
$(window).scroll(function(event){
hasScrolled()
});
setInterval(function() {
// if (didScroll) {
hasScrolled();
// console.log(didScroll);
// }
}, 5);
hasScrolled();
}
function hasScrolled() {
var delta = 5;
var navbarHeight = $('.navbar-wrapper').outerHeight();
var position = $(window).scrollTop();
// console.log($(this))
// console.log(st)
// Make sure they scroll more than delta
if(Math.abs(position) <= delta)
return;
// If they scrolled down and are past the navbar, add class .nav-up.
// This is necessary so you never see what is "behind" the navbar.
if (position > navbarHeight){
// Scroll Down
$('.navbar-wrapper').removeClass('nav-down').addClass('nav-up');
} else {
// Scroll Up
if(position + $(window).height() < $(document).height()) {
// console.log("Scroll up")
$('.navbar-wrapper').removeClass('nav-up').addClass('nav-down');
}
}
}
我当前的代码设法添加了类.nav-up,它在导航栏上放置了-80px,但该规则被我在导航栏上已经拥有的前37.5px覆盖。
答案 0 :(得分:2)
为什么不使用bootstrap?它为您提供所需的一切
答案 1 :(得分:0)
您可以找到功能here的示例。它显示了JQuery和CSS在向下滚动时隐藏导航栏和在向上滚动时显示导航栏的用法。