2012-01-15 105 views
0

我正在使用使用jquery錨鏈接將頁面動畫化爲錨點的較舊腳本。它效果很好,但我需要它只是動畫製作特定div的內容,而不是整個頁面。有關如何定位div而不是頁面的想法?jquery鏈接到動畫滾動div而不是整個頁面

$(document).ready(function() { 
    $("a.anchorLink").anchorAnimate() 
}); 

jQuery.fn.anchorAnimate = function(settings) { 

    settings = jQuery.extend({ 
     speed : 1100 
    }, settings); 

    return this.each(function(){ 
     var caller = this 
     $(caller).click(function (event) { 
      event.preventDefault() 
      var locationHref = window.location.href 
      var elementClick = $(caller).attr("href") 

      var destination = $(elementClick).offset().top; 
      $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() { 
       window.location.hash = elementClick 
      }); 
      return false; 
     }) 
    }) 
} 
+0

就像一般性評論一樣,依靠Javascript的自動分號插入通常是一個糟糕的主意,這是通常被認爲是壞事的語言的「特徵」,如果你不是小心。明確行結束將有助於防止錯誤。如果你真的不喜歡行結尾,也許可以嘗試使用CoffeeScript,而替代語法不需要行結尾,但它生成的JS將是有效的,並且在正確的位置有行結束。 – GregL 2012-01-15 23:51:18

回答

1

你必須改變(如果我的理解對不對你的問題)是下面的代碼的唯一的事:

$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() { 
      window.location.hash = elementClick 
     }); 

,並更改爲

$("#yourDivToAnimateId").animate({ scrollTop: destination}, settings.speed, function() { 
      window.location.hash = elementClick 
     }); 

和你想要的DIV要設置動畫,必須將其id設置爲「yourDivToAnimateId」。有關jQuery選擇器的更多信息,請單擊here

當前代碼動畫整個頁面的原因在於,如果它們目前不是動畫,它會將html和body標記作爲目標。

您還可以使用

$("#yourDivToAnimateId:not(:animated)").animate(...) 

防止選定DIV的一個新的動畫到以前的動畫運行時啓動。

我希望這會有所幫助。

+0

感謝您的回覆。我無法使用上述解決方案使其工作。有沒有一種方法只是使用jquery來動畫div(overflow:scroll;)的內容到該div內的某個ID#? – user1150977 2012-01-16 14:16:39

+0

因此,如果我理解正確的話,你想要動畫化每個嵌套在指定div中的元素,從div的第一個子元素開始,並使用指定的id完成元素?如果是這樣,你在該div中尋找的id是它的直接子,你可以使用[children()](http://api.jquery.com/children/)和[:lt()](http:/ /api.jquery.com/lt-selector/)函數。您可以編輯您的問題以包含js將要處理的實際HTML,以進一步闡明您的需求 – 2012-01-17 21:22:24