主要解决方法是:
1、table的布局保持不变,table外部包裹着一个div,用于设置height和overflow-y:auto
2、使用相对运动保持静止的视觉效果,具体实现是滚轮滚动的距离就是thead在纵向偏移的距离(使用transform: translateY),通过js动态控制
code如下:
1.HTML
<div class="p-l-20 p-r-20 mt-20" id="table-container" style="height: calc(100% - 67px);overflow-y: auto;"> <table class="table"> <thead> <tr> <th nowrap="nowrap" class="left" *ngFor="let head of tableValObj.header">{{head | nullVoid}}</th> </tr> </thead> <tbody> <tr *ngFor="let tr of tableValObj['tbody']"> <td nowrap="nowrap" class="left" *ngFor="let td of tr;let i = index"> <ng-container *ngIf="!td[tableValObj['header'][i]].modifiable && (!td[tableValObj['header'][i]].dataValidation.type || td[tableValObj['header'][i]].dataValidation.type == 1)"> {{td[tableValObj['header'][i]].value}} </ng-container> <ng-container *ngIf="td[tableValObj['header'][i]].dataValidation.type == 3"> <div class="select"> <select [(ngModel)]="td[tableValObj['header'][i]].value"> <option *ngFor="let option of td[tableValObj['header'][i]].dataValidation.data[0]">{{option}}</option> </select> </div> </ng-container> <ng-container *ngIf="td[tableValObj['header'][i]].modifiable && (!td[tableValObj['header'][i]].dataValidation.type || td[tableValObj['header'][i]].dataValidation.type == 1)"> <input style="width: 50%" type="text" [(ngModel)]="td[tableValObj['header'][i]].value"> </ng-container> </td> </tr> </tbody> </table> </div>
2.ts
import { ElementRef } from '@angular/core'; constructor( private elm: ElementRef) { } ngAfterViewInit() { let tableCount = this.elm.nativeElement.querySelector('#table-container'); tableCount.addEventListener('scroll', () => { let scrollTop = tableCount.scrollTop; tableCount.querySelector('thead').style.transform = 'translateY(' + scrollTop + 'px)'; }) }