如何在角度单击时将列表滚动到顶部?

时间:2018-06-30 01:03:19

标签: javascript angular

您能告诉我如何在角度单击按钮时将列表滚动到顶部吗? 我这样尝试过

created_at

它将列表滚动到顶部。但是它隐藏了我的 scrollToTop(el){ el.scrollIntoView(); } <button (click)="scrollToTop(target)">scroll to top</button> ,然后用户看不到addressbar,我认为这不是一个好的解决方案。任何人都有其他好的解决方案

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

2 个答案:

答案 0 :(得分:2)

您可以通过将容器的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 answerbryan60,并适用于RxJS6。您可以在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();
}

答案 1 :(得分: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();    
}