在可滚动的表格中向上滚动标记的行到顶部

时间:2014-10-02 08:32:14

标签: jquery scroll html-table automation

http://jsfiddle.net/3tpqnu1v/

我有一张小桌子并标记了一个特殊的行,其中一个类为“活动”。 如何将这个标记的行自动滚动到该表的顶部或底部或中心:

<table id="table" border="1">
    <thead>
        <tr>
            <th>h1</th>
            <th>h2</th>
            <th>h3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>
        <tr>
            <td>c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>
        <tr>
            <td>c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>
        <tr>
            <td>c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>
        <tr class="active">
            <td>c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>
        <tr>
            <td>c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>
        <tr>
            <td>c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>
        <tr>
            <td>c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>
        <tr>
            <td>c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>
        <tr>
            <td>c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>
        <tr>
            <td>c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>
                <tr>
            <td>c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>
        <tr>
            <td>c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>
        <tr>
            <td>c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>
        <tr>
            <td>c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>
    </tbody>
</table>

1 个答案:

答案 0 :(得分:2)

这样的东西,但是我无法从行中获得完全正确的偏移位置。你需要玩弄正确的ypos。

http://jsfiddle.net/3tpqnu1v/2/

 $('#scroll').on('click',function(e){
    var ypos = $('#table tr.active').offset().top - $("#table").offset().top - $('#table tr.active').height() ;
    $('#table tbody').animate({
        scrollTop: $('#table tbody').scrollTop() + ypos
    }, 500);
 });