2013-08-23 19 views
1

我有以下腳本,允許我添加一個錨鏈接,附加到我的HTML文檔,然後將用戶滾動到網頁上的某個位置點擊時的位置.class.js ScrollTop到div或節標記

HTML:

<li class="about-scroll">About</li> 

的JavaScript:

$('.about-scroll').click(function() { 
    $('body,html').animate({ 
     scrollTop: 646 
    }, 1600); 

    return false; 
}); 

這工作得很好,但是,作爲內容並不總是靜態的(下拉手風琴,一個響應式佈局等),我將如何能夠滾動到特定的#divsection標籤,而不是n頁面上的數字值?

實施例:

<div class="about"> 
    <h3>About</h3> 
    ... 
    ... 
    ... 
</div> <!-- end .about --> 
+0

爲什麼不使用#錨? [W3Schools的](http://www.w3schools.com/html/html_links.asp) –

回答

3

給所述h3一個id,說報頭。然後,你將用href="#header"

HTML

<h3 id="hi">HIIIIII</h3> 
<a href="#hi">Scroll to Top</a> 

jQuery的

$('a').on('click', function (e) { 
    e.preventDefault();     // prevents default action of <a> 
    var target = this.hash,    // gets the href of the <a> 
     $target = $(target);   // puts it as a selector 
    $('html, body').stop().animate({ 
    'scrollTop': $target.offset().top // scrolls to the top of the element clicked on 
    }, 900, 'swing', function() { 
    window.location.hash = target; 
    }); 
}); 
引用click事件

Fiddle

關於這個功能的最大好處是,它是可重複使用的

1

如果你還沒有動畫,你可以ñ去與回答說,只是給你想要去一個ID的元素,並參考它與動畫,你仍然可以使用ID,但找到偏移量和動畫到那裏爲href =「#the_id_you_placed」

$('.about-scroll').click(function() { 
    $('body,html').animate({ 
     scrollTop: $('#the_id_you_placed').offset().top 
    }, 1600); 

    return false; 
});