2012-06-10 18 views

回答

1

我只是將類放入href中。滾動到。

演示:http://jsfiddle.net/lucuma/jK5T3/1/

<a href=".uniqueID" >Go to post</a> 

<div style="height:1300px"></div> 

<div class="uniqueID" id="1234">This is the post </div>​ 

$('a').click(function(e) { 
    e.preventDefault(); 

    var scrollto = $(this).attr('href'); 
    $('html, body').animate({ 
      scrollTop: $(scrollto).offset().top 
     }, 1500); 
}); 

​ 

我不是100%肯定A HREF可以用一個週期開始(至於是有效的代碼工作),所以備用:

<a href="#" data-link="uniqueID" >Go to post</a> 
<div style="height:1300px"></div> 
<div class="uniqueID" id="1234">This is the post </div>​ 

$('a[data-link]').click(function(e) { 
    e.preventDefault(); 

    var scrollto = '.' + $(this).attr('data-link'); 
    $('html, body').animate({ 
      scrollTop: $(scrollto).offset().top 
     }, 1500); 
}); 

最後,您可以在每個div中添加一個錨點,然後在href中像正常的本地哈希鏈接一樣使用它。由於所有這些解決方案都需要JavaScript,我不確定這是否真的很重要,但此解決方案會將href設置爲我們在加載時添加到頁面上的有效本地錨點。你可以在這部分刪除點擊事件,它仍然可以工作,但頁面會跳轉而不是很好地滾動。

演示:http://jsfiddle.net/lucuma/jK5T3/3/

$('#container div').each(function() { 
    $(this).append('<a id="' + $(this).attr('class') + '" />'); 
}); 

$('a').click(function(e) { 
    e.preventDefault(); 

    var scrollto = $(this).attr('href'); 
    $('html, body').animate({ 
      scrollTop: $(scrollto).offset().top 
     }, 1500); 
}); 

+0

優秀。我發現了一個解決方案,我將這個獨特的課程作爲ID附加到課程中,但是我喜歡你的課程,比我現在可以使用動畫課程更好。非常感謝! – elzi

+0

我剛剛通過添加一個帶有ID的錨點來更新答案。如果您刪除了點擊事件(這可以順利滾動),它仍然可以像您可能找到的解決方案一樣工作,只是爲了讓他們全部回答。 – lucuma

+0

@lucuma,在你的第一個例子中,屏幕確實是滾動到元素的,但是當元素在頁面的頂部時它會停止。如果我想在元素在中間時停止,有什麼辦法可以做到這一點? –

相關問題