How to make html table vertically scrollable

前端 未结 9 522
北荒
北荒 2020-12-24 10:39

see jsbin

I have to make my html table vertically scrollable.
I have used below code on tbody tag but its doesn\'t work for me

 <         


        
9条回答
  •  無奈伤痛
    2020-12-24 11:09

    Here's my solution (in Spring with Thymeleaf and jQuery):

    html:

    
    
        
            

    Objects
    Name
    Type
    name
    type

    css:

    @CHARSET "UTF-8";
    #cap span {
        display: table-caption;
        border:2px solid;
        font-size: 200%;
        padding: 3px;
    }
    #hdr {
        display:block;
        padding:0px;
        margin-left:0;
        border:2px solid;
    }
    #bdy {
        display:block;
        padding:0px;
        margin-left:0;
        border:2px solid;
    }
    #objects #bdy {
        height:300px;
        overflow-y: auto;
    }
    #hdr div div{
        margin-left:-3px;
        margin-right:-3px;
        text-align: right;
    }
    #hdr div:first-child {
        text-align: left;
    }
    #bdy div div {
        margin-left:-3px;
        margin-right:-3px;
        text-align: right;
    }
    #bdy div div:first-child {
        text-align: left;
    }
    .Cell
    {
        display: table-cell;
        border: solid;
        border-width: thin;
        padding-left: 5px;
        padding-right: 5px;
    }
    

    javascript:

    $(document).ready(function(){
        var divs = ['#objects'];
        divs.forEach(function(div)
        {
            if ($(div).length > 0)
            {
                var widths = [];
                var totalWidth = 0;
                $(div+' #hdr div div').each(function() {
                    widths.push($(this).width())
                });
                $(div+' #bdy div div').each(function() {
                    var col = $(this).index();
                    if ( $(this).width() > widths[col] )
                    {
                        widths[col] = $(this).width();
                    }
                });
                $(div+' #hdr div div').each(function() {
                    var newWidth = widths[$(this).index()]+5;
                    $(this).css("width", newWidth);
                    totalWidth += $(this).outerWidth();
                });
                $(div+' #bdy div div').each(function() {
                    $(this).css("width", widths[$(this).index()]+5);
                });
                $(div+' #hdr').css("width", totalWidth);
                $(div+' #bdy').css("width", totalWidth+($(div+' #bdy').css('overflow-y')=='auto'?15:0));
            }
        })
    });
    

提交回复
热议问题