2013-07-25 33 views
0

有人可以請解釋爲什麼這不起作用嗎? 理想情況下,當點擊頂部的鏈接時,它應該向下滾動到我的其他課程。 我也不懂這個代碼,所以詳細的解釋會很棒!jQuery scrollTo代碼幫助

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

回答

0

你必須確保有類「scrollto」每個錨具有指向一個類A HREF(或ID的多個建議)。例如:

<a href="#goToThisAnchor" class="scrollto">Scroll to #goToThisAnchor</a> 

點擊上面的錨會向下滾動到具有id="goToThisAnchor

//Put's the click event listeners on anchor elements with class name 'scrollto' 
$('a.scrollto').click(function(){ 
    $('html, body').animate({ //animates the html and body (this makes the scroll effect) 
     scrollTop: $($.attr(this, 'href')).offset().top-25 //choose which element to scroll to in this case it will choose the element that is specified in the "href" of the anchor clicked. offset().top gives the position offset from the TOP of .your_class_name 
    }, 500); //500 is the time in milliseconds it will take to scroll. 
    return false; //cancels your anchor from following it's href 
}); 

我會用一個ID而不是一個類名,滾動到,否則scrollTop的實際建議元素將滾動到第一個具有所看到的「類名」的元素。

你想擁有這種定位的點擊向下滾動到#rulesa:

<a href="#rulesa" class="scrollto">Scroll to #rulesa</a> 

點擊這個錨將滾動你有ID =「rulesa」的元素。注意這個id包含在href中。

我道歉,使用下面的代碼將工作:

$('a.scrollto').click(function(){ 
    $('html, body').animate({ 
    scrollTop: $("#rulespng").offset().top-25 
    }, 500); 
return false; 

您將不得不重新創建此功能要滾動到每個ID錨。這是很好的,如果你希望所有a.scrollto滾動到只有1錨點:如果您使用的原代碼,將更加靈活#rulespng

scrollTop: $($.attr(this, 'href')).offset().top-25 

你只需要頂部列出的一個函數(您也在原始問題中編寫),它將適用於$('a.scrollto')的所有錨點,這取決於上面解釋的錨點的href屬性。

+0

ok謝謝你的幫助。我打算滾動到的對象的id是#rulesa,它有一個.scrollsto類,所以我應該把#rulesa放在你有'your_class_name'的地方嗎? –

+0

@TomSimpson我再次更新了我的答案:p請參閱您需要使標記生效的標記。 – projeqht

+0

@湯姆辛普森,是的,你可以做到這一點。但我原來的答案並不是可擴展的。我會更新答案,以顯示您應該使用您提供的信息的標記。 – projeqht