How do I freeze the first and last columns of an html table in a scrollable div?

前端 未结 7 1477
天涯浪人
天涯浪人 2020-12-28 08:57

I have a table which has a header row, but also a header column and a total column with several columns in between.

Something like this:

Name    Scor         


        
7条回答
  •  Happy的楠姐
    2020-12-28 09:20

    I assume you want to scroll it horizontally only. Otherwise it could be confusing with static columns.

    You could put the overflow: auto onto a containing element of the inner table cells only... I'm not sure how browsers would handle this, but you may be able to put the elements you want fixed inside thead and tfoot elements, and put the scrolling portion inside a tbody element, and set it's overflow to auto.

    Failing that, you may need to drop semantics and code the left column and right column outside the table.

    Personally, I'd try code it as semantic as possible, and then use JavaScript to position the left and right columns. Without JavaScript, you should make it fail gracefully to just a wide table (not sure how difficult this would be, as you say you have a fixed width)

    You could try this (rough) jQuery example to put the first column's values outside.

    var nameTable = ''; // start making a table for name column only
    
    $('#scoreTable tbody tr').each(function() { // iterate through existing table
    
       var nameCol = $(this).find(':first'); // get column of index 0, i.e. first
    
       var cellHeight = nameCol.height(); // get the height of this cell
    
       $(this).find('td').height(cellHeight); // equalise the height across the row so removing this element will not collapse the height if it is taller than the scores and total       
    
       nameTable += ''; // append the next row with new height and data
    
       nameCol.remove(); // remove this cell from the table now it's been placed outside
    
    });
    
    nameTable += '
    Name
    ' + nameCol.html() + '
    '; // finish table string $('#scoreTable').before(nameTable); // insert just before the score table

    Use CSS to position them to align correctly. This is untested, but it should give you some idea.

提交回复
热议问题