最近項目中有個需求,表頭固定,內部實現滾動條。除了單個表頭,還有多個表頭的情況(下一篇中介紹)。
效果圖:
html 結構
按區域劃分可以分爲三個大部分,一共是通過4個table 組合成一個整體的table。
然後通過 col 屬性去設定列的寬度,注意:這裏的寬度必須要設置爲固定值。
表頭過濾功能暫時未實現。
水平滾動效果與垂直滾動效果
監聽主體table(淺綠色部分)滾動事件,同步上下滾動頭部的table (深綠色部分)和 左右滾動左側固定的table(紅色部分中的紫色部分)
代碼 1
$(this.tableContent.nativeElement).on('scroll', (e) => {
$(this.fixedRowWrapper.nativeElement).prop('scrollTop', $(this.tableContent.nativeElement).prop('scrollTop'));
//方式一 :設置頭部固定列table 的滾動條,需要配合less 樣式隱藏滾動條(如果不考慮ie9的兼容性,可以使用。less樣式參考代碼2)
// $(this.tableHeader.nativeElement).prop('scrollLeft', $(this.tableContent.nativeElement).prop('scrollLeft'))
// 方式二:設置頭部固定列table 的margin-left 屬性爲負值,間接實現了頭部固定的列同步向左滾動效果,兼容ie9
$(this.tableHeader.nativeElement).css({ marginLeft: `${-$(this.tableContent.nativeElement).prop('scrollLeft')}px` })
})
代碼 2
.ngx-table__header-inner {
// 隱藏滾動條,頁面div 保持橫向滾動,但是不支持ie9 ,爲了兼容性所以沒有使用,ts 中同步滾動
// 而是動態設置 ngx-table__header-inner 的margin-left 實現滾動效果
overflow: -moz-scrollbars-none;
overflow-x: auto;
-ms-overflow-style: none;
&::-webkit-scrollbar {
width: 0 !important;
display: none;
}
}
完整代碼地址
github項目地址,需要的可以點擊訪問 https://github.com/zjinger/ngx-TPR/tree/master/src/app/components/scroll-table