2010-10-03 32 views
0

我有一個鏈接(index.html#services)和<div id="services>,我試圖改變鏈接被點擊後淡出的背景顏色。我使用的是最新的jQuery和jQuery Color插件,並且:window.location.hash不工作?

$(document).ready(function(){ 
    if(window.location.hash === '#services') { 
     var service = $('#services'); 
     var originalColor = service.css('background-color'); 

     service.css('background-color', '#FFEE9F').animate({ 
      'background-color': originalColor 
     }, 3000); 
    } 
}); 

做高亮,但它不工作。有人知道爲什麼

+0

您還錯過了您的div id的結束報價。 – 2010-10-03 05:34:35

+0

Opps,這不是我的實際代碼,只是在SO上的一個錯字。 – 2010-10-03 05:37:46

回答

3

該代碼僅在加載頁面時運行,而不是在單擊具有散列的鏈接時運行。嘗試直接從新的瀏覽器選項卡鏈接(index.html#services),它可能會工作。你需要做的是在散列被改變時運行該代碼。新的瀏覽器有一個onhashchange事件 - 但在舊瀏覽器上沒有這樣的事情。對於舊的瀏覽器,您可以每隔一段時間輪詢散列屬性以查看它是否已更改。

如果偶然在觸發該動畫的鏈接上有一個特定的標識符(css class,id,name等),您可以添加一個click偵聽器來運行該代碼。例如:

function animateBackground() { 
    var service = $('#services'); 
    var originalColor = service.css('background-color'); 

    service.css('background-color', '#FFEE9F').animate({ 
     'background-color': originalColor 
    }, 3000); 
} 

$(function() { // shortcut to $(document.ready) 
    $('.fade-bg').live('click', animateBackground); 
    animateBackground(); 
}); 
+0

啊,你是對的,我試着從那個鏈接刷新頁面......但實際上它打開了一個新標籤並複製/粘貼它。謝謝!我怎麼才能讓它工作,只要點擊鏈接(這是我的導航的一部分)。 – 2010-10-03 05:36:10

+0

Opps,在看到你編輯的答案之前答覆。你能告訴我怎麼做?我對JS很陌生,或者會問這個問題太多了? – 2010-10-03 05:40:42

+0

再次......你打我反應哈哈。所以,如果我說,按照上面的代碼,'Link'會起作用嗎? – 2010-10-03 05:43:47

0

或者使用

window.onhashchange = function(){ 
    if(window.location.hash === '#services') { 
     var service = $('#services'); 
     var originalColor = service.css('background-color'); 

     service.css('background-color', '#FFEE9F').animate({ 
      'background-color': originalColor 
     }, 3000); 
    } 
}; 

,這取決於你的瀏覽器目標。