zoukankan      html  css  js  c++  java
  • 简单实现固定表格的上表头、左表头

    如果要在一个有限大小的元素里展示一个大表格该怎么办?

    第一步肯定是把这个大表格塞到元素里,然后超出部分用滚动条来查看。

    但是现在问题来了,怎么让一个表格向下滚动的时候上表头不动?向右滚动的时候左表头不动呢?

    先看看效果。

    先贴上JS代码。

    $(document).ready(function(){
        //当父元素滚动时
        $(".bd").scroll(function(){
            //表头根据滚动距离调整相对位置
            $("#headerTop").css({"position":"relative","top":$(".bd").scrollTop(),"z-index":"3"});
            //遍历每一个行
            $("#table tr").each(function(){
                //取每一行第一个元素,即左表头,根据滚动距离调整相对位置
                $(this).children().first().css({"position":"relative","left":$(".bd").scrollLeft(),"z-index":"2"});
            });
        });
    });

    用到的两个方法

    1.监听某个元素的滚动条事件
    $(selector).scroll(function(){.......});
    2.获取滚动条滚动的距离
    $(selector).scrollTop();
    $(selector).scrollLeft();

    然后是CSS代码。

    input { height:22px; }
    .bd { width:200px; height:210px; overflow:scroll; }
    #table { line-height:24px; }
    #table th,#table td { background-color:#fff; }
    #headerTop { background-color:#fff; }
    .headerLeft { width:50px; height:22px;line-height:24px; text-align:center; }

    用两个背景色盖住底层元素,相对位置position:relative;都写在JS里了,当然也可以写在CSS里面。

    最后是HTML

    <body>
        <div class="bd">
            <table id="table">
                <tr id="headerTop">
                    <th>姓名</th>
                    <th>一月</th>
                    <th>二月</th>
                    <th>三月</th>
                    <th>四月</th>
                    <th>五月</th>
                    <th>六月</th>
                    <th>七月</th>
                    <th>八月</th>
                    <th>九月</th>
                    <th>十月</th>
                    <th>十一月</th>
                    <th>十二月</th>
                </tr>
                <tr>
                    <td><div class="headerLeft">成成1</div></td>
                    <td><input /></td>
                    <td><input /></td>
                    <td><input /></td>
                    <td><input /></td>
                    <td><input /></td>
                    <td><input /></td>
                    <td><input /></td>
                    <td><input /></td>
                    <td><input /></td>
                    <td><input /></td>
                    <td><input /></td>
                    <td><input /></td>
                </tr>
            </table>
        </div>
    </html>

    就只贴一行了...

  • 相关阅读:
    正则表达式匹配负数和数字
    下拉框select chosen被遮盖
    获取JavaScript对象的方法
    管理机--Jumpserver由docker搭建
    腾讯云--腾讯云sdk-实现脚本修改腾讯云负载均衡权重
    Linux系统中使用confluence构建企业wiki
    腾讯云--对象存储cos绑定自定义域名
    python(一)python的操作符
    pytest(五)用例传fixture参数
    pytest(四)firture自定义用例预置条件
  • 原文地址:https://www.cnblogs.com/huangjian2/p/5718328.html
Copyright © 2011-2022 走看看