[英]Using jQuery to hide navigation on scroll but reveal on hover
我計划在我的設計頂部進行雙層固定位置導航。
當用戶向下滾動頁面時,我希望導航向上滑動,直到第一層大部分被隱藏。
如果用戶將鼠標懸停在導航上,則容器應向下滑動,再次顯示第一層。
如果用戶位於瀏覽器窗口的頂部,則不應觸發此懸停效果。
此外,當用戶滾動回到頁面的最頂部時,完整的雙層導航應該再次完全可見,因為它在初始加載時。
我在使用javascript將這些事件鏈接在一起時遇到了麻煩,並且不得不求助於CSS3 transitions
和jQuery addClass/removeClass
調用的組合。
另外,我只能將整個混合物搗碎一次。 因此,一旦用戶向下滾動並備份,就不再有動畫了。
我目前的代碼可以在這個小提琴上查看
希望這可以讓我知道我想要做什么。
任何人都可以幫我把這種怪物帶入生活嗎?
代碼如下:
HTML
<div id="nav_wrap">
<div id="nav_one">
<h2>Nav One</h2>
</div>
<div id="nav_two">
<h3>Nav Two</h3>
</div>
</div>
<p>blah blah blah etc...</p>
CSS
#nav_wrap {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 120px;
z-index: 100;
}
#nav_one,
#nav_two {
float: left;
width: 100%;
height: 48px;
background: #111;
}
#nav_two {
background: #1f4c6b;
height: 72px;
}
h2, h3 {
color: #fff;
}
#nav_wrap.fixed {
margin-top: -42px;
-webkit-transition: margin-top .5s ease-in-out;
box-shadow: 0 0 24px #111;
}
#nav_wrap.down {
margin-top: 0px;
-webkit-transition: margin-top .5s ease-in-out;
}
#nav_wrap.drop {
top: 42px;
-webkit-transition: top .5s ease-in-out;
}
#nav_wrap.up {
top: 0;
-webkit-transition: top .5s ease-in-out;
}
使用Javascript
var top = $('#nav_wrap').offset()
.top - parseFloat($('#nav_wrap')
.css('marginTop')
.replace(/auto/, 0));
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y > top) {
$('#nav_wrap').addClass('fixed');
$("#nav_wrap").hover(
function () {
$(this).addClass('drop');
},
function () {
$(this).addClass('up');
}
);
} else if (y == 0) {
$('#nav_wrap').addClass('down');
}
});
你的方法太復雜了。 您實際需要做的就是在JavaScript中滾動一個類滾動。 這個CSS將完成剩下的工作。
注意:代碼需要為其他瀏覽器添加前綴(-moz,-o,-ms),我會考慮在滾動中提高調用的addClass
部分的性能,因為事件將被調用很多。
這里可以找到一個例子。
CSS
#nav_wrap {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 120px;
z-index: 100;
}
#nav_one,
#nav_two {
width: 100%;
height: 48px;
background: #111;
}
#nav_two {
background: #1f4c6b;
height: 72px;
}
h2, h3 {
color: #fff;
}
#nav_wrap{
-webkit-transition: margin-top .5s ease-in-out;
}
#nav_wrap.scroll {
margin-top: -42px;
box-shadow: 0 0 24px #111;
}
#nav_wrap.scroll:hover{
margin-top: 0px;
}
JS
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y > 0) {
$('#nav_wrap').addClass('scroll');
}
else{
$('#nav_wrap').removeClass('scroll');
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.