简体   繁体   English

向下滚动页面时,表格行必须固定在顶部

[英]Table row must stay fixed on the top when scrolling down the page

I would like that <tr> with id="row" stays on top of page, when and only if I scroll page down and falls out of viewed page. 我希望id="row" <tr>停留在页面顶部,当且仅当我向下滚动页面并从查看的页面中掉出来时。 If table heading is viewed on page, this table row it's on his place not on top of page. 如果在页面上查看表标题,则该表行位于他的位置而不位于页面顶部。 I have table: 我有桌子:

<table id="table">
<thead>
    <tr>
        <th>heading of table</th>
    </tr>
</thead>
<tbody>
    <tr id="row">
        <td colspan=3>Search box</td>
    </tr>
    <tr>
        <td>info</td>
        <td>info</td>
        <td>info</td>
    </tr>
    <tr>
        <td>info</td>
        <td>info</td>
        <td>info</td>
    </tr>
    <tr>
        <td>info</td>
        <td>info</td>
        <td>info</td>
    </tr>
    <tr>
        <td>info</td>
        <td>info</td>
        <td>info</td>
    </tr>
</tbody>

<table id="row-fixed"></table>

This is what i've done so far, but it's not working: 这是我到目前为止所做的,但是没有用:

var tableOffset = $("#table").offset().top;
var $header = $("#table > row").clone();
var $fixedHeader = $("#row-fixed").append($header);

$(window).bind("scroll", function() {
var offset = $(this).scrollTop();

if (offset >= tableOffset && $fixedHeader.is(":hidden")) {
    $fixedHeader.show();
}
else if (offset < tableOffset) {
    $fixedHeader.hide();
}
});

What should I change in this code, that would work for <tr id="row"> 我应该在此代码中进行哪些更改,这将适用于<tr id="row">

Here is a working case: http://jsfiddle.net/fj8wM/4489/ 这是一个工作案例: http : //jsfiddle.net/fj8wM/4489/

var $header = $("#table > row").clone(); var $ header = $(“#table> row”)。clone();

Your selector is invalid, you are missing the id hashtag. 您的选择器无效,您缺少ID主题标签。 It should be $("#row").clone(); 应该是$(“#row”)。clone();

First, don't have the search box in a row. 首先,不要连续放置搜索框。 Extract it out of the table to its own element 将其从表中提取到其自己的元素

<div id="row">
    Search box
</div>

Then, apply position:fixed to it and margin-top to the table 然后,将position:fixed应用于它,并将margin-top应用于表格

#row { 
    position: fixed; 
    top: 0px; 
}
#table { 
    margin-top:25px;
}

Finally, there is no need to use javascript/jQuery for this. 最后,无需为此使用javascript / jQuery。

Check out this fiddle 看看这个小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM