动态获取表格(固定表头)实现代码

高洛峰
高洛峰 原创
2017-03-15 09:18:29 1003浏览

这篇文章介绍动态获取表格(固定表头)实现代码

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        p {
            width: 600px;
            height: 300px;
            margin: 0 auto;
            overflow: auto;
            position: relative;
        }

        .tab2 {
            opacity: 0;
            position: absolute;
            top: 0;
        }
        .tab1 td{
            text-align: center;
        }
    </style>
</head>
<body>
<p>

    <table border="1px" cellspacing="0px" class="tab1">
        <thead class="th xh">

        </thead>
        <tbody class="td">

        </tbody>
    </table>
    <table border="1px" cellspacing="0px" class="tab2">
        <thead style="background: #fff" class="th">
        <tr>
        </tr>
        </thead>
    </table>
</p>
</body>
<script src="jquery.js"></script>
<script>
    $('p').scroll(function (x) {
        var $this = $(this),
                viewH = $(this).height(),//可见高度
                contentH = $(this).get(0).scrollHeight,//内容高度
                scrollTop = $(this).scrollTop();//滚动高度
        if (scrollTop > 0) {
            $('.tab2').css({
                "opacity": '1',
                "Z-index": '100',
                "top": scrollTop
            })

        } else if (scrollTop < 30) {
            $('.tab2').css({
                "opacity": '0'
            })
        }
    });

    Data();

    function Data() {
        var data = {

        };
        $.get(url, data, function (res) {

            $('.th').html(res.ReportHeard)
            if($('.tab1 tr th').length < 10){
                $('.tab1').css('width','100%');
                $('.tab2').css('width','100%');
            }else{
                var wd = $('.tab1 tr th').length * 120 + 'px'; // 通过后台返回的表头有多少列,如果少于10列表格100% 大于10则手动添加
                $('.tab1').css('width',wd)
                $('.tab2').css('width',wd)
            }
            var sjObj = JSON.parse(res.ContentList);
            var test = '';
            for (var key in sjObj) {
                test += '<tr>'
                $('.xh th').each(function () {
                    test += '<td>' + sjObj[key][$(this).attr('data')] + '</td>';
                })
                test += '</tr>'
            }
            $('.td').html(test);

       // 循环tabl里的th 看看有多少个  把每个th的宽度赋值给tab2里的th
            $('.tab1 thead th').each(function (i) {
                console.log($('.tab1 thead th').eq(i).width());
                $('.tab2 thead th').eq(i).width($('.tab1 thead th').eq(i).width())

            })

        })
    }

</script>
</html>

以上就是动态获取表格(固定表头)实现代码的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。