Angular2-6 實現吸頂效果指令
阿新 • • 發佈:2019-01-08
做專案的時候需要用到吸頂效果,可是沒有找到單獨的外掛,所以自己實現一個吸頂的指令.
思路為檢測需要吸頂的元素是否滾動到頂部,為其加上fixed屬性
auto-fixed.directive.ts
@Directive({
selector: '[txAutoFixed]'
})
export class AutoFixedDirective {
// 元素距離頂部的原始距離
toTop: number = 0;
// 吸頂元素
toTopElement: any;
// 吸頂元素id
// tslint:disable-next-line:no-input-rename
@Input ('txAutoFixed') selector: string = '';
@HostListener('scroll', ['$event'])
onScroll($event: Event) {
if (this.er.nativeElement.scrollTop >= this.toTop) {
this.renderer2.setStyle(this.toTopElement, 'position', 'fixed');
} else {
this.renderer2.setStyle(this.toTopElement, 'position' , 'static');
}
}
constructor(private er: ElementRef, private renderer2: Renderer2) {
setTimeout(() => {
this.toTopElement = this.er.nativeElement.querySelector('#' + this.selector);
this.toTop = this.toTopElement.offsetTop;
}, 0);
}
}
指令作用於滾動容器,傳入吸頂元素的id,初始化時獲取吸頂元素的資料並儲存,對滾動進行監聽.
用法:
<div class="container" txAutoFixed="fixedElement">
<div>
<div id="fixedElement">
吸頂元素
</div>
</div>
</div>
吸頂元素需要使用一個父容器包裹並設定同樣的高度,避免元素脫離,列表佈局變動.
不確定高度的吸頂元素可以通過複製來實現,也可以想其他辦法.
效果:
這隻適合用於自己寫的頁面,在使用ng-weui庫使,使用infiniteloader時因為滾動在元件裡面,沒法監聽,只能重寫該元件實現.思路差不多.