2013-02-27 55 views
1

只是第一個「其他」不起作用。向下滾動時,topColor div會從原來的15高增加到150高,但當我在靠近頂部滾動時,不會縮回到15高。Animate Height - Else Not Working

$(document).ready(function() { 
    $(window).scroll(function() { 
     if ($(this).scrollTop() > 20) { 
      $('#topColor').animate({ 
       height: "150px" 
      }); 
     } else { 
      $('#topColor').animate({ 
       height: "15px" 
      }); 
     } 
     if ($(this).scrollTop() > 300) { 
      $("#fixedMenuBar").fadeIn('slow', 'linear'); 
     } else { 
      $("#fixedMenuBar").fadeOut('fast', 'linear'); 
     } 
    }); 
}); 
+0

什麼是$(本).scrollTop()的值?使用console.log($(this).scrollTop())登錄到控制檯。 – teewuane 2013-02-27 21:29:14

回答

1

你不應該使用else在滾動responsed動畫,使用else if而不是爲更加具體和animate會產生衝突,因爲滾動值會改變的,和jQuery不能無限重複相同的動畫。

但是如果你堅持animate試試這個:

var scrollVal = $(this).scrollTop(); 

    if (scrollVal < 20) 
     if ($("#fixedMenuBar").is(':visible')) { 
     $("#fixedMenuBar").fadeOut('fast', 'linear'); 
     } 
     if (parseInt($('#topColor').css('height')) != 150) { 
     $('#topColor').animate({ height: "150px" }); 
     } 

    }else if (scrollVal >= 20 && scrollVal < 300) { 
     if ($("#fixedMenuBar").is(':visible')) { 
     $("#fixedMenuBar").fadeOut('fast', 'linear'); 
     } 
     if (parseInt($('#topColor').css('height')) != 15) { 
     $('#topColor').animate({ height: "15px" }); 
     } 

    }else if (scrollVal >= 300) { 
     if (!$("#fixedMenuBar").is(':visible')) 
     $("#fixedMenuBar").fadeIn('slow', 'linear'); 
    } 

這個答案也應該可以幫助您:Setting CSS value limits of the window scrolling animation

+0

+1,你還應該檢查元素'$()。是(':animated')'以防止大動畫查詢 – HenningCash 2013-02-27 21:42:09

+0

謝謝......我的第一個jQuery嘗試。我添加了您的代碼...但現在我的網站不加載。將它包裝在$(document).ready(function()和$(window).scroll(function()中。 – Brett 2013-02-27 22:58:24

+0

剛剛使用.scrollTop和translateY將對象向下和向後滑動。你的時間! – Brett 2013-02-28 01:06:07