一、table固定表头滚动(不兼容IE) 使用scrollTop监听滚动 如下例
1、html
<div class="tabflow" id="flowtable-cont"> <table> <thead><tr><th>年度</th><th>起降架次(万架)</th><th>旅客吞吐(万人)</th><th>货邮吞吐(万吨)</th></tr></thead> <tbody> <tr><td>2011</td><td>512</td><td>600</td><td>376</td></tr> <tr><td>2012</td><td>504</td><td>593</td><td>397</td></tr> <tr><td>2013</td><td>562</td><td>562</td><td>381</td></tr> <tr><td>2014</td><td>705</td><td>464</td><td>302</td></tr> <tr><td>2015</td><td>784</td><td>443</td><td>374</td></tr> <tr><td>2016</td><td>645</td><td>504</td><td>415</td></tr> <tr><td>2017</td><td>534</td><td>534</td><td>432</td></tr> <tr><td>2018</td><td>375</td><td>582</td><td>460</td></tr> <tr><td>2019</td><td>397</td><td>621</td><td>442</td></tr> </tbody> </table> </div>
2、css
.tabflow{width: 100%;height: 17vh;overflow: auto;display: none;} .tabflow table{font-size: 0.14rem;color: #5a5a5a; width: 100%;} .tabflow table tr{text-align: center;line-height: 0.25rem;border: 1px solid #f2f2f2;border-right: none;} .tabflow table thead{background-color: #fff;} .tabflow table tbody tr:nth-child(2n+1){background-color: #f2f2f2;} .tabflow table tbody tr td{font-size: 0.125rem;}
3、js
window.onload = function(){ var tableflow = document.querySelector('#flowtable-cont'); //获取table元素
function scrollHandle (e){ console.log(this) var scrollTop = this.scrollTop; this.querySelector('thead').style.transform = 'translateY(' + scrollTop + 'px)'; } tableflow.addEventListener('scroll',scrollHandle); //监听scroll事件 }
二、table固定表头滚动(兼容IE) 更改css, 设置固定宽度
css
table{border-collapse: collapse;} table{font-size: 0.14rem;color: #5a5a5a; width: 100%;position: relative;} table tr{text-align: center;line-height: 0.25rem;border: 1px solid #f2f2f2;border-right: none;} table thead{background-color: #fff;position: fixed;z-index: 3;} table thead tr th{width: 1.2rem;} table thead tr th:first-child{width: 0.4rem;} table tbody{top: 0.25rem;position: absolute;overflow: auto;height: 15vh;} table tbody tr:nth-child(2n+1){background-color: #f2f2f2;} table tbody tr td{font-size: 0.125rem;width: 1.2rem;} table tbody tr td:first-child{width: 0.4rem;}
效果