2014-03-03 94 views
0

這應該相當簡單,但jquery不是我的強項。添加淡入淡出頂端

我正在尋找添加一個簡單的淡入/淡出時,CSS類被添加到元素,這發生在偏移量後。我知道淡入淡出階段,但我不知道如何在這個場合實現它。

Fidde here

jQuery(function(){ 
    var menuOffset = jQuery('.header-bar')[0].offsetTop; 
    jQuery(document).bind('ready scroll',function() { 
    var docScroll = jQuery(document).scrollTop(); 
    if(docScroll >= menuOffset) { 
     jQuery('#navigationtop').addClass('fixed').css('width',jQuery('#masthead').width()); 
    } else { 
     jQuery('#navigationtop').removeClass('fixed').removeAttr("width"); 
    } 
    }); 
}); 
+0

你可以做出的jsfiddle?此外,只要你可以使用$而不是jQuery! –

+0

生病了。必須使用$,因爲它在wordpress – memyselfandmyiphone

+0

@Ivinvinhan小提琴添加 – memyselfandmyiphone

回答

0

像這樣

http://jsfiddle.net/j32t2/4/

CSS - 最初隱藏

.fixed { 
    position:fixed; 
    width:100%; 
    z-index: 700; 
    top:0; 
    display: none; 
} 

JS - 枯萎了它,如果它已不存在

jQuery(function(){ 
    var menuOffset = jQuery('.header-bar')[0].offsetTop; 
    jQuery(document).bind('ready scroll',function() { 
    var docScroll = jQuery(document).scrollTop(); 
    if(docScroll >= menuOffset) { 
     if(!jQuery('#navigationtop').hasClass('fixed')) { 
      jQuery('#navigationtop').addClass('fixed docked').css('width',jQuery('#masthead').width()).fadeOut(0).fadeIn(1000); 
     } 
    } else { 
     if(jQuery('#navigationtop').hasClass('docked')) { 
      jQuery('#navigationtop').removeClass('docked'); 
      jQuery('#navigationtop').fadeOut(1000, function() { 
       $(this).removeClass('fixed').removeAttr("width").show(); 
      }); 
     } 
    } 
    }); 
}); 

請注意我沒有添加fadeOut。固定類的檢查是需要的或它會不斷淡入。對於某些文檔,http://api.jquery.com/fadein/http://api.jquery.com/fadeOut/

+0

嗨@黃會。感謝你的回答。工作得很好,只是一個不會淡出的恥辱。 :) – memyselfandmyiphone

+0

我已經添加了淡出,你可以檢查小提琴,看看它是如何工作的。 – Huangism

0

您只需在默認情況下隱藏它。我喜歡做的是使用.stop(true, true)來停止當前可能正在運行的任何動畫。然後我使用.hide(0)即時刪除菜單。剩下的就是添加課程並通過.fadeIn('slow')淡入課程。

jQuery的


jQuery(function() { 
    var menuOffset = jQuery('.header-bar')[0].offsetTop; 
    jQuery(document).bind('ready scroll', function() { 
     var docScroll = jQuery(document).scrollTop(); 
     if (docScroll >= menuOffset) { 
      jQuery('#navigationtop') 
       .stop(true, true) 
       .hide(0) 
       .addClass('fixed') 
       .fadeIn('slow'); 
     } else { 
      jQuery('#navigationtop') 
       .removeClass('fixed'); 
     } 
    }); 
}); 


CSS


#navigationtop { 
    width: 100%; 
    height: 30px; 
    background-color: blue; 
} 
.fixed { 
    position: fixed; 
    z-index: 700; 
    top: 0; 
} 


See working jsFiddle demo

+0

嗨。我喜歡你的答案,但當菜單出現後,我滾動,它重新加載時閃爍 – memyselfandmyiphone

+0

當我運行示例時它會淡入淡出 –

+0

這沒有檢查停靠的類,這就是爲什麼它繼續淡入,如果你繼續滾動 – Huangism