如何使用jquery向下滚动到div的特定子节点

时间:2011-09-23 20:55:01

标签: jquery scroll

如何向下滚动到div的第n个子节点。考虑一下这段代码

 <span id="click_me">Click me to scroll down to nth child</span>

消息div有6个孩子。我想向下滚动到有人点击“click_me”的第3个或第4个孩子

注意:动态添加子项。使用一些ajax函数调用/ juggernaut推送通知。

<div class="messages" id="messages_212">
    <div class="message_container">
        <p><b>Sahil grover: </b>5</p> 
    <div>
    <div class="message_container">
        <p><b>Sahil grover: </b>4</p> 
    <div>
    <div class="message_container">
        <p><b>Sahil grover: </b>3</p> 
    <div>
    <div class="message_container">
        <p><b>Sahil grover: </b>2</p> 
    <div>
    <div class="message_container">
        <p><b>Sahil grover: </b>1</p> 
    <div>

    <div class="message_container">
        <p><b>Sahil grover: </b>0</p> 
    <div>
</div>

3 个答案:

答案 0 :(得分:4)

我不使用jQuery(或任何框架),但在纯JavaScript中很容易做到:

d = document.getElementById('messages_212');
d.scrollTop = d.children[2].offsetTop;
// children[2] for the third div, [3] for the fourth, etc.

答案 1 :(得分:1)

使用http://plugins.jquery.com/project/ScrollTo

插件主页和文档:http://flesler.blogspot.com/2007/10/jqueryscrollto.html

//scroll to nth child
var child = 3;
$.scrollTo($(".message_container")[child]);

//scroll to nth child
var child = 3;
$.scrollTo("#messages_212:nth-child("+child+")");

答案 2 :(得分:0)