html固定表头

 <style>
        .fixedHead {
            top: 0;
            position: fixed;
            display: flex;
            background-color: #cfe7ed;
        }
        .fixedHead2 {
            top: 30px;
            position: fixed;
            display: flex;
            background-color: #cfe7ed;
        }
    </style>
    <script>
        $(document).ready(function () {
            var tr = $('tbody>tr:first');
            var trtwo = $('th[colspan]');
            if (tr != undefined && tr != null && tr.length > 0) {
                var newhead = tr.clone();
                var newhead2 = $('table').clone();
                newhead2.find('tr:gt(1)').remove();
                var tr_top = tr.offset().top;
                if (trtwo != undefined && trtwo.length > 0) {
                    $(document).scroll(function () {
                       
                        if ($(window).scrollTop() > tr_top) {
                          
                            $('table').before(newhead2);
                            newhead2.addClass('fixedHead');
                           
                            var tds = $('tbody:eq(1)>tr:eq(2) td');
                            var header = newhead2.find('tr:eq(1)').find('th');
                            var colgap=tds.length-header.length ;//列的差额
                            if (colgap>0) {//得到合并单元格数量                   
                                newhead2.find('tr:eq(0)').find('th').each(function (i, e) {
                                    if (i <= colgap) {
                                        $(e).attr('width', tds.eq(i).width());
                                    }
                                });
                            };
                            newhead2.find('tr:eq(1)').find('th').each(function (i, e) {
                                $(e).attr('width', tds.eq(i + colgap).width());
                            });
                            
                            console.log('tds length is ' + tds.length);
                            console.log('header is ' + newhead2.find('tr:eq(1)').find('th').length);
                        } else {
                            newhead2.remove();
                        }
                    })
                } else {
                    $(document).scroll(function () {


                        if ($(window).scrollTop() > tr_top) {
                            tr.parent().append(newhead);
                            newhead.addClass('fixedHead');
                            var tds = $('tbody>tr:eq(1) td');
                            newhead.find('th').each(function (i, e) {
                                $(e).attr('width', tds.eq(i).width());
                            });
                        } else {
                            newhead.remove();
                        }
                    })
                }
            }
        });
    </script>

猜你喜欢

转载自blog.csdn.net/pengdayong77/article/details/55100985
今日推荐