How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

后端 未结 13 2176
攒了一身酷
攒了一身酷 2020-11-27 03:11

How can I create a table that has its first row and first column both locked, as in Excel, when you activate \'freeze panes\'? I need the table to both scroll horizontally

13条回答
  •  遥遥无期
    2020-11-27 03:50

    I did this with a combination of:

    • Using multiple tables
    • Fixed-size cells
    • jQuery's scrollTop and scrollLeft functions

    Here's a jsfiddle example to demonstrate.

    Haven't tested on all browsers but I imagine it's not great on older IE versions.

    $("#clscroll-content").scroll(function() {
        $("#clscroll-row-headers").scrollTop($("#clscroll-content").scrollTop());
        $("#clscroll-column-headers").scrollLeft($("#clscroll-content").scrollLeft());
    });
    
    $("#clscroll-column-headers").scroll(function() {
        $("#clscroll-content").scrollLeft($("#clscroll-column-headers").scrollLeft());
    });
    
    $("#clscroll-row-headers").scroll(function() {
        $("#clscroll-content").scrollTop($("#clscroll-row-headers").scrollTop());
    });
    .clscroll table {
        table-layout: fixed;
    }
    
    .clscroll td, .clscroll th { 
        overflow: hidden;
    }
    
    .corner-header {
        float: left;
    }
    
    .column-headers {
        float: left;
        overflow: scroll;
    }
    
    .row-headers {
        clear: both;
        float: left;    
        overflow: scroll;
    }
    
    .table-content {
        table-layout: fixed;
        float: left;
        overflow: scroll;
    }
    
    .clscroll td, .clscroll th { 
        width: 200px;
        border: 1px solid black;
    }
    
    .row-headers, .table-content {
        height: 100px;
    }
    
    .column-headers, .table-content, .table-content table, .column-headers table {
        width: 400px;
    }
    
    
     
    Bus Plane Boat Bicycle
    Red
    Green
    Blue
    Orange
    Purple
    Yellow
    Pink
    Brown
    Red Bus Red Plane Red Boat Red Bicycle
    Green Bus Green Plane Green Boat Green Bicycle
    Blue Bus Blue Plane Blue Boat Blue Bicycle
    Orange Bus Orange Plane Orange Boat Orange Bicycle
    Purple Bus Purple Plane Purple Boat Purple Bicycle
    Yellow Bus Yellow Plane Yellow Boat Yellow Bicycle
    Pink Bus Pink Plane Pink Boat Pink Bicycle
    Brown Bus Brown Plane Brown Boat Brown Bicycle

提交回复
热议问题