2013-10-10 101 views
2

我想滾動頁面到錨點鏈接。我使用下面的代碼:jQuery滾動不起作用錨點

$('a').click(function(){ 
     $('html, body').animate({ 
      scrollTop: $($(this).attr('href')).offset().top 
     }, 400); 
     return false; 
    }); 

它工作正常,如果我有這樣的網址:

<a href="#comments">Comments</a> 

然而,問題是通過在末尾添加#,網址是自動生成的所以它會是:

<a href="http://example/sth/#comments">Comments</a> 

在這個原因,它不起作用。我無法更改URL的標記,我如何修復jQuery以使用此類url?

回答

3

可以讀取錨,而不是它的hash酒店的href

$('a').click(function(){ 
    $('html, body').animate({ 
     scrollTop: $(this.hash).offset().top 
    }, 400); 
    return false; 
}); 

http://jsfiddle.net/KL5uw/

+0

很酷的做法,不知道你可以做一個錨點URL,+1 :) –

+0

非常感謝你,這是很大的幫助:) – user2738640

0

滾動到特定的錨標記,這可以用HTML只有

前完成:

<a name="top"></a> // where we have to reach 
<a href="#top">last</a>  // we reach their by clicking on this we can also use an image, align in right 

Demo