Implementation of fixed table headers in a responsive table to respond to table Headers
When data is displayed, the header is fixed for better readability.
I. Implementation Method:
1. Define two tables with a fixed absolute
<Div class = "table1-wapper"> <table width = "100%" cellpadding = "0" cellspacing = "0" id = "table1"> <tr> <th> <div> serial number </div> </th> <div> stock name </div> </th>... </tr> <tr>... </tr> </table> </div> <div class = "fixed-table1-wapper"> <table width = "100%" cellpadding = "0" cellspacing = "0" id =" fixed-table1 "> </table> </div>
2. Copy Table 1 <th> and insert Table 2
var th_new=$("#table1 tr").eq(0).clone();$("#fixed-table1").append(th_new);
3. The resize () method is used to obtain the <th> width of each column in table 1 in real time.
function trResize(){$("#fixed-table1 th").each(function(){var num=$(this).index();var th_width=$("#table1 th").eq(num).width();$(this).css("width",th_width+"px");});}
4. After page hours, the table will scroll with the table Header
$(".table1-wapper").scroll(function(){var scroll=-$(this).scrollLeft()$(".fixed-table1-wapper").css("left",scroll+"px");});
Ii. Pay attention to the details:
1. Adaptive width and Cell Gap removal:
<Table width = "100%" cellpadding = "0" cellspacing = "0"> </table>
2. Table line:
Directly <td> Add border, and the edge will overlap. Add the attribute border-collapse: collapse;
3. td width:
Control the width of the first line. <td width = "70"> </td>/<td width = "20%"> </td>
4. The color of the parity line is different:
Css: # table1 tr: nth-child (2n) {background-color: # ccc;} ie7 compatibility problem
Jquery: $ ("# table1 tr: even" ).css ("background-color", "# ccc ");
The complete code is as follows:
<! Doctype html> $ ("# Table1 tr: even" ).css ("background-color", "# ccc"); // the color of the odd/even row var inner_width = $ ("# table1 "). outerWidth (); $ (". fixed-table1-wapper ").css (" width ", inner_width +" px "); var th_new = $ (" # table1 tr "). eq (0 ). clone (); $ ("# fixed-table1 "). append (th_new) ;}) $ (window ). resize (function () {trResize () ;}); $ (". table1-wapper "). scroll (function () {var scroll =-$ (this ). scrollLeft () $ (". fixed-table1-wapper ").css (" left ", scroll +" px ") ;}); function trResize () {var inner_width =$ (" # table1 "). outerWidth (); $ (". fixed-table1-wapper ").css (" width ", inner_width +" px "); $ (" # fixed-table1 th "). each (function () {var num = $ (this ). index (); var th_width = $ ("# table1 th "). eq (num ). width (); // console. log ("th_width:" descrith_width?#((this=.css ("width", th_width + "px") ;}</script> </body>