基于colResizable-1.6实现一个表头固定、列宽可调的table

colResizable官网:http://www.bacubacu.com/colresizable/

  • 能够实现各列完全对齐
  • 能够兼容有无滚动条两种情况
  • 只能在表头部分拖动改变列宽(不能在表体列边框上拖动,我可以接受)
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
    table {
        border-collapse: collapse;
        width: 100%;
        /* 关键样式 */
        table-layout: fixed;
    }
    .table-header tr th {
        border: 1px solid red;
    }
    .table-body-wrapper {
        border: 1px solid red;
        height: 75px;
        overflow-x: hidden;
        overflow-y: auto;
    }
    .table-body tr td {
        border-right: 1px solid red;
        border-bottom: 1px solid red;
        /* 关键样式:不设置padding:0会导致无法完全对齐 */
        overflow: hidden;
        padding-left: 0 !important;
        padding-right: 0 !important;
    }
    </style>
</head>

<body>
    <div class="table-header-wrapper">
        <table class="table-header">
            <tr>
                <th> header </th>
                <th> header header </th>
                <th> header </th>
            </tr>
        </table>
    </div>
    <div class="table-body-wrapper">
        <table class="table-body">
            <tr>
                <td> cell </td>
                <td> cell </td>
                <td> cell </td>
            </tr>
            <tr>
                <td> cell </td>
                <td> cell </td>
                <td> cell </td>
            </tr>
            <tr>
                <td> cell </td>
                <td> cell </td>
                <td> cell </td>
            </tr>
            <tr>
                <td> cell </td>
                <td> cell </td>
                <td> cell </td>
            </tr>
            <tr>
                <td> cell </td>
                <td> cell </td>
                <td> cell </td>
            </tr>
        </table>
    </div>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script src="colResizable-1.6.min.js"></script>
    <script type="text/javascript">
    $(function() {
        $(".table-header").colResizable({
            liveDrag: true,
            onDrag: syncCol
        });
        //页面加载完成后,手动对齐一次
        syncCol();
        //window resize的时候,会出现列不完全对齐的情况,手动对齐
        $(window).resize(function() {
            syncCol();
        });
    });

    function syncCol() {
        $('.table-body tr:first-child td').each(function() {
            $(this).width($('.table-header tr th:eq(' + $(this).index() + ')').css('width'));
        });
    }
    </script>
</body>

</html>

资源地址:https://download.csdn.net/download/fukaiit/11848465

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值