2013-02-26 29 views
1
$(window).scroll(function() { 
if ($(window).scrollTop() > 100) { 
    $('.nav').css('margin-top', '5px'); 
    $('.sep').css('margin-top', '20px'); 
    $('.logo').fadeOut(500); 
    $('#navWrap').animate({ 
     height: '62px' 
     }, 500, function() { 
     }); 
} 
} 
); 
$(window).scroll(function() { 
if ($(window).scrollTop() < 100) { 
     $('.nav').css('margin-top', '23px'); 
    $('.sep').css('margin-top', '40px'); 
    $('.logo').fadeIn(500); 
} 
} 
); 

我有這段代碼,當你向下滾動時,我的導航動畫高度從100px到62px,我試圖讓它動畫回到100px,當你再次到達頂部,但似乎無法這樣做。上下導航動畫高度

我通常在第二個窗口中包含.animate .scroll函數,但它沒有做任何事情。

回答

1

你很近,只需要進行一些修改。

  • 首先,您需要跟蹤導航器的當前狀態。否則,每當你滾動時,你都會添加一個新的請求,使其變大或變小。你只想觸發動畫時,你從頂部穿過100個「門檻」。
  • 其次,您想在動畫之前調用stop(),否則向下滾動然後向上將導致每個新動畫進入隊列,導航欄將繼續打開和關閉。
  • 三,你不需要兩個電話$(window).scroll ...你有一個獨特的條件。要麼你超過或低於100,並且只有在你尚未這樣做時才執行CSS更改和動畫。把它放到同一個功能中可以更容易管理。

var navsize = "large"; 
$(window).scroll(function() { 
    if ($(window).scrollTop() > 100) { 
     if (navsize == "large") 
     { 
      navsize = "small"; 
      $('.nav').css('margin-top', '5px'); 
      $('.sep').css('margin-top', '20px'); 
      $('.logo').stop().fadeOut(500); 
      $('#navWrap').stop().animate({ 
       height: '62px' 
      }, 500); 
     } 
    } 
    else 
    { 
     if (navsize == "small") 
     { 
      navsize = "large"; 
      $('.nav').css('margin-top', '23px'); 
      $('.sep').css('margin-top', '40px'); 
      $('.logo').stop().fadeIn(500); 
      $('#navWrap').stop().animate({ 
       height: '100px' 
      }, 500); 
     } 
    } 
}); 
+0

完美的作品就像一個魅力! – 2013-02-26 04:23:23

+0

這種方法的一個問題是它每次觸發滾動事件都會進行動畫處理。理想情況下,我會用CSS3轉換來做到這一點,但至少要將'.stop()'改爲'.stop(true,true)'以防止動畫隊列填滿。 – Blender 2013-02-26 04:25:50

+1

@Blender在這種情況下,隊列中永遠不會有多個事件。我認爲徽標淡出和淡入淡出可能也需要一個「停止()」。毫無疑問,在看到這個很酷的效果之後,用戶會在滾動條上上下滾動滾動條,看看會發生什麼。 – Plynx 2013-02-26 04:35:49