粘滞标题列与表列不匹配

时间:2013-09-04 21:18:21

标签: javascript jquery html css twitter-bootstrap

根据此example.,我在表格中有一个“持久标题” 该表本身是使用Bootstrap 2.3构建的 我的问题:如果滚动,表标题列与表列不匹配。

没有滚动: enter image description here

点击向下滚动: enter image description here

HTML:

<div id="page-wrap">
<table class="table table-hover persist-area">
    <thead>
        <tr class="persist-header">
            <th></th>
            <th style="text-align:right"></th>
            <th style="text-align:right">one</th>
            <th style="text-align:right">two</th>
            <th style="text-align:right">three</th>
            <th style="text-align:right">four</th>
            <th style="text-align:right">five</th>
            <th style="text-align:right">six</th>
            <th style="text-align:right">seven</th>         
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
            </td>
            <td style="text-align:right;">
            </td>
            <td style="text-align:right">
            </td>
            <td style="text-align:right">
            </td>
            <td style="text-align:right">
                blublu
            </td>
            <td style="text-align:right">
            </td>
            <td style="text-align:right">
            </td>
            <td style="text-align:right">
            </td>
            <td style="text-align:right">
            </td>
        </tr>
    </tbody>
</table>

CSS:

*   { 
margin: 0; 
padding: 0; 
}
h1 {
margin: 0 0 20px 0;
}
p {
margin: 0 0 20px 0;
}
#page-wrap { 
margin: 50px auto;
}
table {
border-collapse: collapse;
}
th { 
width: 200px;
}

/*this one is the replacement for scrolling*/
.floatingHeader {
  position: fixed;
  top: 40px;
  visibility: hidden;
  background-color: #fff;
  border-bottom: 2px solid #E4205C;
}

JS:

function UpdateTableHeaders() {
$(".persist-area").each(function() {

    var el         = $(this),
    offset         = el.offset(),
    scrollTop      = $(window).scrollTop(),
    floatingHeader = $(".floatingHeader", this)

    if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
        floatingHeader.css({
            "visibility": "visible"
        });
    } else {
        floatingHeader.css({
            "visibility": "hidden"
        });      
    };
});
}

$(function() {
var clonedHeaderRow;
$(".persist-area").each(function() {
    clonedHeaderRow = $(".persist-header", this);
    clonedHeaderRow
    .before(clonedHeaderRow.clone())
    .css("width", clonedHeaderRow.width())
    .addClass("floatingHeader");

});

$(window)
.scroll(UpdateTableHeaders)
.trigger("scroll");

});

jsfiddle DEMO

1 个答案:

答案 0 :(得分:0)

This解决了我的问题。

/* apply a natural box layout model to all elements */
*, *:before, *:after {
  -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;
 }