http://runjs.cn/detail/e5xzyjmh <!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>RunJS 演示代码</title> <style type="text/css"> #box{ height:214px; width:700px; overflow-y:auto; position:relative; } table,tr,td,th{ border:1px solid #ccd; border-collapse:collapse; } table{ width:100%; } td{ height:24px; width:80px; line-height:24px; padding:3px 5px; background-color:#ddd; word-break:break-all; } th{ height:24px; width:80px ; line-height:24px; background-color:#cfc; } </style> </head> <body> <div id="box"> <table id="tab"> <tr> <th> 固定表头第一列 </th> <th> 固定表头第二列 </th> <th> 固定表头第三列 </th> <th> 固定表头第四列 </th> <th> 固定表头第五列 </th> <th> 固定表头第六列 </th> </tr> <tr> <td>A1</td> <td>A2</td> <td>A3</td> <td>A4</td> <td>A5</td> <td>A6</td> </tr> <tr> <td>B1</td> <td>B2</td> <td>B3</td> <td>B4</td> <td>B5</td> <td>B6</td> </tr> <tr> <td>C1</td> <td>C2</td> <td>C3</td> <td>C4</td> <td>C5</td> <td>C6</td> </tr> <tr> <td>D1</td> <td>D2</td> <td>D3</td> <td>D4</td> <td>D5</td> <td>D6</td> </tr> <tr> <td>E1</td> <td>E2</td> <td>E3</td> <td>E4</td> <td>E5</td> <td>E6</td> </tr> <tr> <td>F1</td> <td>F2</td> <td>F3</td> <td>F4</td> <td>F5</td> <td>F6</td> </tr> <tr> <td>G1</td> <td>G2</td> <td>G3</td> <td>G4</td> <td>G5</td> <td>G6</td> </tr> <tr> <td>H1</td> <td>H2</td> <td>H3</td> <td>H4</td> <td>H5</td> <td>H6</td> </tr> <tr> <td>A1</td> <td>A2</td> <td>A3</td> <td>A4</td> <td>A5</td> <td>A6</td> </tr> <tr> <td>B1</td> <td>B2</td> <td>B3</td> <td>B4</td> <td>B5</td> <td>B6</td> </tr> <tr> <td>C1</td> <td>C2</td> <td>C3</td> <td>C4</td> <td>C5</td> <td>C6</td> </tr> <tr> <td>D1</td> <td>D2</td> <td>D3</td> <td>D4</td> <td>D5</td> <td>D6</td> </tr> <tr> <td>E1</td> <td>E2</td> <td>E3</td> <td>E4</td> <td>E5</td> <td>E6</td> </tr> <tr> <td>F1</td> <td>F2</td> <td>F3</td> <td>F4</td> <td>F5</td> <td>F6</td> </tr> <tr> <td>G1</td> <td>G2</td> <td>G3</td> <td>G4</td> <td>G5</td> <td>G6</td> </tr> <tr> <td>H1</td> <td>H2</td> <td>H3</td> <td>H4</td> <td>H5</td> <td>H6</td> </tr> </table> </div> </body> <script type="text/javascript"> function scroll(viewid,scrollid,size){ var scroll = document.getElementById(scrollid); var tb2 = document.getElementById(viewid).cloneNode(true); var len = tb2.rows.length; for(var i=tb2.rows.length;i>size;i--){ tb2.deleteRow(size); } var bak = document.createElement("div"); bak.style.width = scroll.clientWidth+'px'; scroll.appendChild(bak); bak.appendChild(tb2); bak.style.position = "absolute"; bak.style.backgroundColor = "#cfc"; //表头背景颜色,请保持和css中定义颜色一样 bak.style.display = "block"; bak.style.left = 0; bak.style.top = "0px"; scroll.onscroll = function(){ bak.style.top = this.scrollTop+"px"; } } //上面是方法,等页面加载完之后调用方法 //第一个参数是表格的ID,第二个参数是滚动条容器的ID,第三个参数是表头的行数 window.onload = function (){ scroll("tab","box",1); } </script> </html> 提示:你可以先修改部分代码再运行。 转载请注明:有爱前端 » js 表头固定 喜欢 (0)or分享 (0)