【问题标题】:how to scroll the list to top on button click in angular?如何在按钮单击时将列表滚动到顶部?
【发布时间】:2018-12-09 04:35:15
【问题描述】:

您能否告诉我如何在 angular 中单击按钮时将列表滚动到顶部? 我试过这样

 scrollToTop(el){
    el.scrollIntoView();
  }

  <button (click)="scrollToTop(target)">scroll to top</button>

它将列表滚动到顶部。但它隐藏了我的addressbar,然后用户看不到header 我认为这不是一个好的解决方案。任何人都有其他好的解决方案

这是我的代码 https://stackblitz.com/edit/angular-f9qxqh?file=src%2Fapp%2Fapp.component.html

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    您可以通过将容器的scrollTop 属性设置为零来滚动到列表顶部。有关演示,请参阅 this stackblitz

    <div #container class="container">
      <ul>
        <li *ngFor="let i of items">{{i}}</li>
      </ul>
    </div>
    
    <button (click)="container.scrollTop = 0">scroll to top</button>
    

    这是一个简单的方法,可以平滑滚动到列表顶部。它基于this answer by bryan60,并适用于RxJS 6。您可以在this stackblitz中试用。

    <button (click)="scrollToTop(container)">scroll to top</button>
    
    import { interval as observableInterval } from "rxjs";
    import { takeWhile, scan, tap } from "rxjs/operators";
    ...
    
    scrollToTop(el) {
      const duration = 600;
      const interval = 5;
      const move = el.scrollTop * interval / duration;
      observableInterval(interval).pipe(
        scan((acc, curr) => acc - move, el.scrollTop),
        tap(position => el.scrollTop = position),
        takeWhile(val => val > 0)).subscribe();
    }
    

    【讨论】:

    • 示例就像我们在jquery 中所做的那样,让duration 完成此任务。目前它快速移动到顶部。我们可以给出持续时间
    • 可以在this post找到一些纯Javascript平滑滚动的代码。
    • 我添加了一个平滑滚动的方法,基于 Observables。
    【解决方案2】:

    您将scroll 添加到您的容器中,因此它适用于容器而不是ul

    app.component.html

    <div class="container" #container>
      <ul #target>
        <li *ngFor="let i of items">{{i}}</li>
      </ul>
    </div>
    <button (click)="scrollToTop(container)">scroll to top</button>
    

    app.component.ts

    scrollToTop(el) {
     el.scrollTop = 0;          
    }
    

    为了平滑滚动,使用这个:

    scrollToTop(el) {
        var to = 0;
        var duration = 1000;
        var start = el.scrollTop,
            change = to - start,
            currentTime = 0,
            increment = 20;
    
        var easeInOutQuad = function(t, b, c, d) {
            t /= d / 2;
            if (t < 1) 
                return c / 2 * t * t + b;
            t--;
            return -c / 2 * (t * (t - 2) - 1) + b;
        }
    
        var animateScroll = function() {        
            currentTime += increment;
            var val = easeInOutQuad(currentTime, start, change, duration);
    
            el.scrollTop = val;
            if(currentTime < duration) {
                setTimeout(animateScroll, increment);
            }
        }
        animateScroll();    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 2014-11-24
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      • 2015-01-12
      相关资源
      最近更新 更多