2015-05-15 59 views
2

我正在爲網站創建導航菜單。當用戶滾動過點497px時,它需要改變顏色。我已經寫了這個劇本:JQuery偏移腳本

$(document).ready(function(){ 

    function checkOffset() { 
     var offset = $(document).scrollTop(); 
     console.log(offset); 
     if(offset > 497){ 
      $("#fixedBar").animate({backgroundColor: '#1B1B1B'}, 1000); 
      $("#fixedBar nav a").animate({color: '#FFF'}, 1000); 
     }else{ 
      $("#fixedBar").animate({backgroundColor: '#FFF'}, 1000); 
      $("nav a").animate({color: '#1B1B1B'}, 1000); 

     } 
     } 
    $(window).scroll(function() { 
     checkOffset(); 
    }); 

    }); 

如果我刷新頁面,這是過去的那個點,然後它確實改變了,但是如果我只是滾過這一點,然後它不會改變。我怎樣才能解決這個問題?

+0

您的腳本可能有效。但是因爲你在每張卷軸上製作動畫。有連續動畫週期的機會。我的建議是先暫時將'animate'改爲'css'方法,看看它是否有效。如果確實如此,請確保在動畫之前調用'stop()',請參閱URL https://api.jquery.com/stop/ –

+0

是的。 – Jon

+0

然後,讓我添加這個答案。讓這對其他人也有用。 –

回答

1

您的腳本可能有效。

但是因爲您在每張卷軸上都有動畫。有連續動畫週期的機會。

可能的解決方案將是(這些點中的任何一個),

  1. 要使用任意css方法,而不是animate
  2. 動畫應該幫助之前執行stop()
  3. 執行animate方法

要知道在jQuery的更多stop()前檢查現有的顏色值。

0

你應該調用checkOffset();多一次:

$(document).ready(function(){ 

    function checkOffset() { 
     var offset = $(document).scrollTop(); 
     console.log(offset); 
     if(offset > 497){ 
      $("#fixedBar").animate({backgroundColor: '#1B1B1B'}, 1000); 
      $("#fixedBar nav a").animate({color: '#FFF'}, 1000); 
     } else { 
      $("#fixedBar").animate({backgroundColor: '#FFF'}, 1000); 
      $("nav a").animate({color: '#1B1B1B'}, 1000); 
     } 
    } 
    $(window).scroll(function() { 
     checkOffset(); 
    }); 

    checkOffset(); // <-- HERE 

}); 
+0

是什麼原因? – kosmos

1

要使用帶顏色的.animate(),您需要使用jQueryUI。因此,該框架添加到您的頭上:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js""></script> 

然後再試一次(我修改了一點當前的代碼):

$(function(){ 
    $(window).on('scroll', function() { 
     checkOffset(); 
    }); 
}); 

function checkOffset() { 
    var $target = $('#fixedBar'); 
    var offset = $(window).scrollTop(); 
    console.log(offset); 
    if(offset >= 10){ 
     $target.stop(true, false).animate({ 'background-color': 'green'}, 1000); 
     //$("#fixedBar nav a").animate({color: '#FFF'}, 1000); 
    } 
    else if(offset < 10){ 
     $target.stop(true, false).animate({ 'background-color': 'blue' }, 1000); 
     //$("nav a").animate({color: '#1B1B1B'}, 1000); 
    } 
} 

Check the jsFiddle