当用户向下滚动页面时,我的页面顶部出现了一个粘性导航栏,此刻它突然弹出/出现在页面上。使用来自 How to build floating menu bar when scroll down 的以下代码
//jQuery Code
//Sticky Nav
var top = jQuery(‘#mydiv’).offset().top - parseFloat(jQuery(‘#mydiv’).css('marginTop').replace(/auto/, 100));
jQuery(window).scroll(function (event) {
// what the y position of the scroll is
var y = jQuery(this).scrollTop();
// whether that's below the form
if (y >= top) {
// if so, ad the fixed class
jQuery(‘#mydiv’).addClass('fixed');
} else {
// otherwise remove it
jQuery(‘#mydiv’).removeClass('fixed');
}
});
//CSS
#mydiv.fixed {
position: fixed;
top: 0;
left: 0;
z-index: 1;
width: 100%;
border-bottom: 1px solid #000;
padding: 10px 0px 0px 3%;
background:#FFFFFF;
font-size: 85% !important;
}
我想给它添加一个过渡效果,当它出现时淡入,当菜单消失时淡出。
我尝试将主线 jQuery 代码更新为
//whether that's below the form
if (y >= top) {
// if so, ad the fixed class
//jQuery(‘#mydiv’).addClass('fixed');
jQuery(‘#mydiv’).css({'position': 'fixed', 'top': '0px', 'opacity':'0', 'left':'0', 'z-index':'1', 'width':'100%', 'border-bottom':'1px solid #000', 'padding':'10px 0px 0px 3%', 'background':'#FFFFFF'}).animate({opacity:1},300);
虽然它会在导航出现时过渡/淡入,但只要有滚动,菜单就会出现故障/闪烁。
如果有人可以告诉我如何正确地做到这一点,任何帮助都会很棒
最佳答案
您可以将您的代码保留在类中(这样更简洁),只需使用 jQuery 的 .fadeIn()
函数而不是动画不透明度。
if (y >= top) {
// if so, add the fixed class
jQuery('#mydiv').addClass('fixed').fadeIn();
} else {
// otherwise remove it
jQuery('#mydiv').removeClass('fixed').fadeOut();
}
另一个不错的方法是让条形图从顶部平滑地动画化。您可以在 CSS 中完全做到这一点:
#mydiv{
position: fixed;
top: -100px; //height of the div
left: 0;
z-index: 1;
width: 100%;
border-bottom: 1px solid #000;
padding: 10px 0px 0px 3%;
background:#FFFFFF;
font-size: 85% !important;
-webkit-transition: top 0.5s;
transition: top 0.5s;
}
#mydiv.fixed {
top: 0;
}
如果您使用的是 CSS 解决方案,则不需要 fadeIn()
函数。
关于jquery - 将过渡淡入淡出应用到 css jQuery 中的粘性导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29230661/