2012-06-22 117 views
0

我對特定錨鏈接使用Google的平滑滾動腳本#tothetop,而不是僅與任何#。我在example.js文件做到了這一點(您下載的腳本):特定錨鏈接的平滑滾動

更改:

$('a[href*=#]').click(function() { ... }); 

要:

$('a[href*=#tothetop]').click(function() { ... }); 

所以現在它僅適用於平滑滾動到#tothetop,但我將如何將它應用到其他不同的錨鏈接?例如:#tothetop#tothebottom,#gotothepub等等。 (爲什麼我不使用「#」不要問,因爲這是一個很長的故事,但在很短 - 它與頁面上的其他腳本衝突) 我試過:

$('a[href*=#tothetop]','a[href*=#tothebottom]').click(function() { ... }); 

但是這並未沒有工作。 我對Javascript和PHP不太瞭解,但我確信有一個簡單的方法可以做到這一點?對於example.js

的完整代碼是這樣:

$(function(){ 

$('a[href*=#tothetop]').click(function() { 

if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
    && location.hostname == this.hostname) { 

     var $target = $(this.hash); 

     $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']'); 

     if ($target.length) { 

      var targetOffset = $target.offset().top; 

      $('html,body').animate({scrollTop: targetOffset}, 1000); 

      return false; 

     } 

    } 

}); 

}); 
+0

應該還有jquery標籤嗎? –

回答

1

我會用這個,因爲很明顯,你的名字你滾動錨所有「toTheAnchor」:

$('body').on('click', 'a[href^=#][href*=to]', function() {}); 

這應該選擇開始以「#」的所有鏈接,並有「向」字。

+0

邪惡!謝謝你,它現在正在工作:)我只希望其他問題不會出現。從來不知道JavaScript是多功能的:) – MSchumacher

+0

如果他們這樣做,只需在stackoverflow上創建一個線程;) – Simon

1

$('a[href^="#"]').click(...); 

這個選擇嘗試將匹配在href屬性開始#所有錨。

你舉的例子是有效的,但它應該這樣寫這樣

$('a[href*="#tothetop"], a[href*="#tothebottom"]') 

注意周圍的值引號和單引號(只使用一次)。

+0

WOW - 快速回復!我不能只使用「#」因爲它與我的頁面上的另一個腳本衝突(長篇故事)...我已經在上面的問題中添加了這個解釋。雖然謝謝! – MSchumacher

+0

對不起,我沒有在你的代碼中看到^。小^意味着什麼? – MSchumacher

+0

'^ ='表示以值*開頭的屬性*,而'* ='表示包含該值的屬性* – fcalderan