粘貼性屬性
.sticky {
position: sticky;
left: 0;
}
至少應指定top
、right
、bottom
最近滾動祖先
如果要兩個屬性都靠左
.company {
position: sticky;
left: 0px;
}
.manager {
position: sticky;
left: 120px;
}
需要計算位置
計算示例
- 表格位置 = (100, 200) // <-- x = 100
Company
位置 = (100, 200) // <-- x 相對於表 = 100 - 100 = 0Manager
的位置 = (300, 200) // <-- x 相對於表 = 300 - 100 = 200
要減去table
距離左側的距離
Optional
可以理解我是兒子,通過這個屬性拿到父母給我的管道或者指令
舉個小栗子
app.component
<div one>
<div two></div>
</div>
在two
指令中, 我們可以通過Optional
拿到one
的指令和app.component
的組件
twoDirective
constructor( @Optional() private one: oneDirective,@Optional() private app:appComponent) {
}
上完整的案例
<table appStickyTable style="width: 900px;overflow-x: auto;margin-left:200px;">
<tr>
<th appSticky>Company</th>
<th appSticky>Manager</th>
<th>Employees</th>
<th>Contractors</th>
<th>Jobs</th>
<th>Contracts</th>
</tr>
<ng-container *ngFor="let item of data">
<tr>
<td appSticky style="min-width:200px">{{ item.a }}</td>
<td appSticky>{{ item?.a }}</td>
<td> {{ item?.b }} </td>
<td> {{ item?.c }} </td>
<td> {{ item?.d }} </td>
<td> {{ item?.f }} </td>
</tr>
</ng-container>
</table>
data:any = [
{a: 111, b: 222, c: 333, d: 444, f: 555},
{a: 111, b: 222, c: 333, d: 444, f: 555},
{a: 111, b: 222, c: 333, d: 444, f: 555},
{a: 111, b: 222, c: 333, d: 444, f: 555},
]
td,th{
width: 200px;
text-align: center;
background-color: #fff;
}
table的指令,主要是拿到距離左側的距離
@Directive({
selector: '[appStickyTable]'
})
export class StickyTableDirective {
constructor(private el: ElementRef) {
}
get x() {
return (this.el.nativeElement as HTMLElement)?.getBoundingClientRect().x;
}
}
appSticky
指令
@Directive({
selector: '[appSticky]'
})
export class StickyDirective implements AfterViewInit {
constructor(private el: ElementRef,
@Optional() private table: StickyTableDirective,@Optional() private One:Text1Component) {
}
ngAfterViewInit() {
console.log(this.One);
const el = this.el.nativeElement as HTMLElement;
const { x } = el.getBoundingClientRect();
el.style.position = 'sticky';
el.style.left = this.table ? `${x - this.table.x}px` : '0px';
}
}