加载中...

Angular2-6 实现吸顶效果指令

博客 2025.05.23 14:08 1080

做项目的时候需要用到吸顶效果,可是没有找到单独的插件,所以自己实现一个吸顶的指令. 思路为检测需要吸顶的元素是否滚动到顶部,为其加上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>

吸顶元素需要使用一个父容器包裹并设置同样的高度,避免元素脱离,列表布局变动. 不确定高度的吸顶元素可以通过复制来实现,也可以想其他办法.

效果:

20180720154740156.gif

在使用ng-weui库使,使用infiniteloader时因为滚动在组件里面,没法监听,只能重写该组件实现.思路差不多.