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

nav*_*een 4 javascript angular

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

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

  <button (click)="scrollToTop(target)">scroll to top</button>
Run Code Online (Sandbox Code Playgroud)

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

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

Con*_*Fan 6

您可以通过将scrollTop容器的属性设置为零来滚动到列表顶部。有关演示,请参阅此 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>
Run Code Online (Sandbox Code Playgroud)

这是一个简单的方法,可以平滑地滚动到列表的顶部。正是基于此答案bryan60,并适用于RxJS 6.你可以尝试在此stackblitz

<button (click)="scrollToTop(container)">scroll to top</button>
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)


Jag*_*ngh 5

你添加scroll到你的容器,所以它适用于容器而不是ul

应用程序组件.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>
Run Code Online (Sandbox Code Playgroud)

app.component.ts

scrollToTop(el) {
 el.scrollTop = 0;          
}
Run Code Online (Sandbox Code Playgroud)

为了平滑滚动,请使用:

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();    
}
Run Code Online (Sandbox Code Playgroud)