简体   繁体   中英

Making the first column of a table fixed on horizontal scroll

Thanks for Reading. I have a table inside a div container(div0).The table is populated with data and is dynamically generated. So the height and width of table is not fixed.The outer div can be scrolled both vertically and horizontally to view the entire table. Now the requirement is that I need to fix the poistion of first column of the table horizontally ie On scrolling the horizontal scrollbar, the first column should be fixed and rest should scoll. Just need some pointers on this, on how to achive this?

I am thinking of separating the first column contents (which is not scrollable horizontally) in a div(div1), and other the scrollable contentents in separate div(div2) both placed in table with one row and 2 tds. Now I am getting 2 probs with this approach, 1 the scrollbar of div 2 is getting inside the div0 when I scroll right(Thought of using a jquery scrollbatr but how to position it outside the div2). Second is the alignent between the two divs.

If I understand what your looking for; I did something similar not too long ago.

Html could look something like this.

<table border="1" id="header">
    <tr>
       <th></th>
       <th></th>
    </tr>
 </table>
 <div id="tableData">
   <table border="1" id="table">
       <td></td>
       <td></td>
   </table>
 </div>

CSS

#tableData {
   overflow: scroll;
   overflow-x:hidden;
   height: 190px;
   border-bottom: 1px solid #B5B3B3;
   width: 940px;
}

JavaScript to make sure the header aligns with the table data

$("#tableData").height(190);
$("#tableData").width(940);
for(var i=1;i<8;i++){
    if($("#header th:nth-child("+i.toString()+")").width() >= $("#table td:nth-child("+i.toString()+")").width())
        $("#table td:nth-child("+i.toString()+")").width($("#header th:nth-child("+i.toString()+")").width());
    else
        $("#header th:nth-child("+i.toString()+")").width($("#table td:nth-child("+i.toString()+")").width());
}
$("#tableData").width($("#table").width()+20);
if($("#table").height() <= $("#tableData").height()) 
   $("#tableData").height($("#table").height());

You might need to make some tweaks but that is one solution. The i variable needs to cover each column, in my example it would work for 7 columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM