HTML 实现表头固定且双向滚动条

网上找了许多种方法,可能学疏才浅,本人并没有实现,或者方法并不能满足大表单(双向滚动条)的需求;

1.大致思路:使用两个table,保证head和body宽度一致即可,以下例子,为完全展示body中每个单元格内容,故动态生成表头,根据已经生成的表单宽度去设定表头宽度;然后保证两个div 公用滚动条。
2.实现单元格内容自动换行或者自动以...代替的关键点在于:设定单元格宽度

直接上demo

<html>
<head>
    <title>表头固定</title>
    <style>
        table.table_head {
            table-layout: fixed;  //在此固定表头宽度,使表头和内容对齐
        }

        table.table_head thead {
            background: grey;
        }
        table.table_head th {
            text-align: center;
            overflow: hidden;
            text-overflow: ellipsis; //表头宽度是根据内容设定的,设置相关属性,超出长度以省略号代替
        }
        table.table_body{
        }
        table.table_body td{
            text-align:left;
            min-width: 100px; //设定内容单元格最小宽度
        }
    </style>
</head>
<body>
<div>
    <div id="head" style="width: 583px;overflow:hidden; "
onscroll="document.getElementById('body').scrollLeft = this.scrollLeft;"> //两个div共用横向滚动轴
        <table class="table table-bordered table-hover table_head" >
            <thead>
            <tr id="column_name"></tr>
            </thead>
        </table>
    </div>
    <div id="body" style="width: 600px;height:300px; overflow:scroll;"
onscroll="document.getElementById('head').scrollLeft = this.scrollLeft;"> //两个div共用横向滚动轴
        <table class="table table-bordered table-hover table_body">
            <tbody id="column_value">
            <tr>
                <td id="1" nowrap='nowrap'> 第一
                </td>
                <td id="2" nowrap='nowrap'> 第二
                </td>
                <td id="3" nowrap='nowrap'> 第三
                </td>
                <td id="4" nowrap='nowrap' > 第四
</td>
                <td id="5" nowrap='nowrap' > 第五
</td>
            </tr>
            </tbody>
        </table>
    </div>
</div>
<script>
$(function () {
        var withs = [];
for (var j = 1; j < 6; j++) {
            withs.push(document.getElementById(j).offsetWidth);
}
        //动态生成表头
$.each(withs, function (i, value) {
            var withsVal = withs[i] + "px";
var a = "<th data-toggle=\"tooltip\"  title=\"" + value + "\" " +
                    "style=\" width: " + withsVal + "\">" +" asdfkjhaskfjhaslkfjhaslkfjhaslfkjhsal" +
                    "</th>";
$("#column_name").append(a);
});
});
</script>
</body>
</html>

猜你喜欢

转载自marcoxiao.iteye.com/blog/2317464