Implementation steps
1. Place the table in a scrollable container;
2. The outer layer of the scrollable container also needs a container, the container must be set out of range hiding and positioning (relative, absolute line);
3. Clone a target table using a script, adjust the column width of the clone table is the same as the original table, hide the tbody, append to the outer container;
4. Listen for scrolling events of the scrolling container, dynamically adjust the left offset of the clone table, the upper offset does not need to be adjusted because it is fixed.
Effect Demo
<style>
. tablebox{height:300px;overflow:auto;width:100%;}
. tableboxcontainer table Td{white-space:nowrap;}
. tableboxcontainer table Thead{background: #ddd;}
. Tableboxcontainer{position:relative;width:300px;overflow:hidden;}
</style>
<link href= "Https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel= "stylesheet" >
<body>
<div class= "Tableboxcontainer" >
<div class= "Tablebox" id= "Tablebox" >
<table class= "Table" >
<thead>
<tr>
<td> column 1</td><td> column 2</td><td> column 3</td><td> column 4</td><td> column 5</ Td>
<td> column 6</td><td> column 7</td><td> column 8</td><td> column 9</td><td> column 10</ Td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script src= "Https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js" ></script>
<script>
$ (function () {
Generate table test data
var $table =$ ("#tablebox"). Find ("table");
var $tbody = $table. Find ("tbody");
for (Var i=0;i<20;i++) {
var $tr =$ ("<tr>");
for (Var j=0;j<10;j++) {
$tr. Append (function () {
Return $ ("<td>"). Text ("line:" + (i+1) + "column:" + (j+1));
});
}
$tr. AppendTo ($tbody);
}
Clone the original table, append to the outermost container
var $table _fixed= $table. Clone ();
var colwidths=[];
Set the column width of a cloned table
$tbody. Find ("Tr:eq (0)"). Find ("TD"). each (function () {
var width=$ (this). Width () +parsefloat ($ (The). CSS ("Padding-left")) +parsefloat ($ (this). CSS ("Padding-right"));
Colwidths.push (width);
});
$table _fixed.find ("Thead TD"). each (function (i) {
$ (this). Width (colwidths[i]);
});
$table _fixed.css ({"position": "Absolute", "left": 0, "top": 0, "table-layout": "Fixed"});
$table _fixed.find ("tbody"). Hide ();//Hides the tbody of the cloned table
$ ("#tablebox"). Parent (). Append ($table _fixed);
Monitoring scrolling events for the original table container
$ ("#tablebox"). Bind ("scroll", function () {
var left=$ (this). ScrollLeft ();
$table _fixed.css ({"Left":-left});
});
});
</script>
</body>
Web Front end Learning Communication Group 21 598399936
Implementation of HTML Fixed table header