div在div

时间:2018-11-15 14:12:43

标签: angular scroll angular2-directives

我正在尝试创建一条指令,以跟踪放置在该元素上的元素的Y位置-当该元素到达父div的顶部时,我将添加粘性样式以使标头一直粘贴到顶部,直到整个元素已滚动。

我尝试跟踪滚动,但是除了初始的ngoninit日志之外,什么也无法得到:

import { Directive, OnInit, ElementRef, HostBinding, HostListener } from '@angular/core';

@Directive({
    /* tslint:disable-next-line:directive-selector */
    selector: '[stickyHeaderDirective]'
})
export class StickyHeaderDirective implements OnInit {


    ngOnInit() {
        console.log('lets track ths scroll');
    }

    constructor() {}

    @HostListener('scroll', ['$event']) private onScroll($event: Event): void {
        console.log($event.srcElement.scrollLeft, $event.srcElement.scrollTop);
    }   
}

我想念什么?

2 个答案:

答案 0 :(得分:0)

HostListener仅侦听scroll元素上发生的[stickyHeaderDirective]事件。该元素必须是引发scroll事件的元素。

确保[stickyHeaderDirective]元素具有正确的CSS样式以使其滚动。这是一个演示,展示了使用和不使用CSS样式的区别。

for (let element of document.getElementsByClassName('track-scrolling')) {
  element.addEventListener('scroll', e => {
      console.log(e.srcElement.scrollLeft, e.srcElement.scrollTop);
  });
}
.container {
  height: 200px;
  width: 200px;
  overflow: auto;
  margin: 10px;
  border: 1px solid;
}

.big-content {
  height: 1000px;
  width: 1000px;
}

.track-scrolling.wrong {
  /*
  No overflow property
  No height/width or max-height/width
  */
  color: red;
}

.track-scrolling.right {
  overflow: auto;
  max-height: 100%;
  
  color: green;
}
<div class="container">
  <div class="track-scrolling wrong">
  I won't fire scroll events
    <div class="big-content"></div>
  </div>
</div>

<div class="container">
  <div class="track-scrolling right">
  I will fire scroll events
    <div class="big-content"></div>
  </div>
</div>

这是一个演示与您的指令相同的行为的演示:https://stackblitz.com/edit/angular-kqvraz

答案 1 :(得分:0)

如果只需要向下滚动,请将其添加到div

 #scrollMe [scrollTop]="scrollMe.scrollHeight"

   <div class="my-list" #scrollMe [scrollTop]="scrollMe.scrollHeight">
   </div>