【问题标题】:How to run a function only when scroll down near the bottom?如何仅在底部附近向下滚动时运行功能?
【发布时间】:2016-06-16 19:48:03
【问题描述】:

我使用的是angular2-infinite-scroll 0.1.4 版。

我的朋友是here

是的,它只在您滚动时在开头运行一次onScrollDown()

我尝试将infiniteScrollDistance 更改为20.8。但都失败了。

只有在靠近底部向下滚动时,我才能运行onScrollDown()

@Component({
  selector: 'my-app',
  directives: [InfiniteScroll],
  styles: [`
    .search-results {
      height: 20rem;
      overflow: scroll;
    }
  `],
  template: `
    <div class="search-results"
         infinite-scroll
         [infiniteScrollDistance]="0.8"
         [immediateCheck]="true" 
         (scrolled)="onScrollDown()">
      <p *ngFor="let i of array">
        {{i}}
      </p>
    </div>
  `
})
export class App {
  array = [];
  sum = 20;

  constructor() {
    for (let i = 0; i < this.sum; ++i) {
      this.array.push(i);
    }
  }

  onScrollDown () {
    console.log('near the bottom!!');

    // add another 20 items
    const start = this.sum;
    this.sum += 20;
    for (let i = start; i < this.sum; ++i) {
      this.array.push(i);
    }
  }
}

【问题讨论】:

  • 为什么 onScrollDown() 在初始页面加载时运行?
  • @AngJobs 对不起,因为[immediateCheck],我删除了它。现在onScrollDown() 不会在初始页面加载时运行。

标签: typescript angular


【解决方案1】:

试试这个:创建一个跟踪鼠标移动的可观察对象,仅在鼠标接近底部时触发但仅发出值。例如:

const mouseMove$ = Observable.fromEvent(document, 'mousemove')
                      .filter(event => event.clientY > SOME_VALUE);

SOME_VALUE 需要根据文档高度计算。

然后创建第二个跟踪滚动事件的 observable:

const scroll$ = Observable.fromEvent(document, "scroll");

然后将两者结合起来:创建一个仅在鼠标在页面底部移动并且用户正在滚动时才会发出值的 observable:

const combined$ = Observable.combineLatest(
    mouseMove$, scroll$
);

然后订阅它:

combined$.subscribe(
    combined => {
       console.log("this the mouse event", combined[0]);
       console.log("this the scroll event", combined[1]);

       // user is scrolling at the bottom of the page, add action here
    }
);

【讨论】:

  • 谢谢,但有一点需要改进,当使用 Mac 触摸板滚动时,'mousemove' 事件不会触发。
【解决方案2】:

尝试在某处使用 onScroll 来捕获窗口滚动事件...类似这样,然后抛出您的函数,该函数将在内部执行您想要的任何操作。

javascript

window.onscroll = function() {
    console.log("scrolling");
};

jQuery

$(window).on('scroll', function() {
    console.log("scrolling");
});

还有一些函数/方法会返回窗口或视口的顶部和底部(无论您需要什么,如果它是原始的 javascript、jQuery 或其他框架),然后在点您希望您的功能启动。

【讨论】:

    【解决方案3】:

    对于我的问题,我需要将height: 20rem; 更改为height: 100%;,然后才能正常工作。 Working plunker.

    另外,@orizens 在我询问后在 angular2-infinite-scroll 的 README.md 文件中添加了一个 official demo


    如果你不想使用 angular2-infinite-scroll, @Angular University 使用 RxJS 给出了一个很好的方向。请检查他的答案。

    【讨论】:

      猜你喜欢
      • 2011-08-02
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      • 2013-01-11
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多