【问题标题】:applying transition fade in fade out to sticky nav in css jQuery在 css jQuery 中应用淡入淡出到粘性导航的过渡淡入淡出
【发布时间】:2015-05-27 15:32:59
【问题描述】:

当用户向下滚动页面时,我的页面顶部出现了一个粘性导航栏,此时它突然弹出/出现在页面上。使用来自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 css navbar


    【解决方案1】:

    您可以将代码保留在类中(更简洁),并且只需使用 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() 函数。

    【讨论】:

    • 嗨 @Dark Ashelin 感谢您的回复,当我这样做时 // 如果是这样,请添加固定类 jQuery('#mydiv').addClass('fixed').fadeIn(); } else { // 否则删除它 jQuery('#mydiv').removeClass('fixed').fadeOut();我的导航栏在页面加载时消失,然后在我向下滚动时淡入,当我滚动到顶部时消失。我是否应该有 2 个导航栏,一个隐藏在屏幕外的导航栏,然后在我向下滚动时淡入该导航栏???是否有另一种方法可以在没有 2 个相同的导航栏/复制它们的情况下做到这一点?
    • 如果你想让它流畅,最好的方法是有2个导航栏是的。您无法为 position 属性设置动画。
    • 好的 @Dark Ashelin 感谢您的帮助,现在在 2 个菜单上淡入淡出效果很好,我不再需要 removeClass,只要我拿出它就可以无缝工作,再次感谢寻求帮助!
    猜你喜欢
    • 2020-03-29
    • 2012-02-04
    • 1970-01-01
    • 2020-03-30
    • 2021-10-01
    • 2011-08-05
    • 2020-08-24
    • 2012-10-11
    • 1970-01-01
    相关资源
    最近更新 更多