【问题标题】:Chrome - On adding elements to *ngFor view always scroll down to last elementChrome - 在向 *ngFor 视图添加元素时,始终向下滚动到最后一个元素
【发布时间】:2021-01-27 14:03:56
【问题描述】:

我有一个包含视频列表的简单页面。在页面底部,我有“加载更多”按钮。如果用户单击该按钮,我会发出 http 请求并将数据添加到现有的视频数组中。

简化后的代码如下所示:

组件:

export class AppComponent implements OnInit {
  public videoList = [];

  constructor(private appService: AppService) {}

  public ngOnInit(): void {
    this.loadVides();
  }

  public loadMore(): void {
    this.loadVides();
  }

  private loadVides(): void {
    this.appService.loadVideos().subscribe((videos) => {
      this.videoList = [...this.videoList, ...videos];
      console.log('Data was loaded');
    })
  }

}

模板:

<div *ngFor="let video of videoList">
  <div style="height: 100px;">{{video.name}}</div>
</div>  


<div class="d-flex justify-content-center mt-2 mb-4">
  <button class="btn btn-outline-danger btn-lg" (click)="loadMore()">Load more...</button>
</div>

有什么问题:

在加载更多项目后,Firefox 页面不会滚动,所以我看到了第一个新项目。在 chrome 中,页面滚动到最后,所以我再次看到最后一个新项目和“加载更多”按钮。

演示:

https://stackblitz.com/edit/angular-ivy-quwfxx?devtoolsheight=33&file=src/app/app.component.html

【问题讨论】:

    标签: css angular twitter-bootstrap google-chrome bootstrap-4


    【解决方案1】:

    您可以像这样添加overflow-anchor:none:-

    <div *ngFor="let video of videoList">
      <div style="height: 100px;">{{video.name}}</div>
    </div>  
    
    
    <div style="overflow-anchor:none" class="d-flex justify-content-center mt-2 mb-4">
      <button class="btn btn-outline-danger btn-lg" (click)="loadMore()">Load more...</button>
    </div>
    

    overflow-anchor 属性使我们能够选择退出 滚动锚定,这是一种浏览器功能,旨在允许内容加载到用户当前 DOM 位置之上而不更改内容完全加载后用户的位置。

    我参考了这个答案 - https://css-tricks.com/almanac/properties/o/overflow-anchor/

    【讨论】:

      【解决方案2】:

      你可以模糊你的按钮,所以 chrome 不会试图稳定滚动位置

      <button class="btn btn-outline-danger btn-lg" #btn (click)="btn.blur(); loadMore()">Load more...</button>
      

      【讨论】:

        猜你喜欢
        • 2018-10-16
        • 1970-01-01
        • 1970-01-01
        • 2019-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-10
        相关资源
        最近更新 更多