如何在角度单击时将列表滚动到顶部? [英] how to scroll the list to top on button click in angular?
问题描述
能否请您告诉我如何在角度单击按钮时将列表滚动到顶部?我这样尝试过
could you please tell me how to scroll the list to top on button click in angular ? I tried like this
scrollToTop(el){
el.scrollIntoView();
}
<button (click)="scrollToTop(target)">scroll to top</button>
它将列表滚动到顶部.但是它隐藏了我的地址栏
,然后用户看不到 header
.我认为这不是一个好的解决方案.其他任何人都没有.解决方案
It scroll the list to top .but it hide my addressbar
and then user not able see header
I think it is not a good solution .anybody have any other good solution
这是我的代码 https://stackblitz.com/edit/angular-f9qxqh?file = src%2Fapp%2Fapp.component.html
推荐答案
您可以通过将容器的 scrollTop
属性设置为零来滚动到列表顶部.有关演示,请参见此stackblitz .
You can scroll to the top of the list by setting the scrollTop
property of the container to zero. See this stackblitz for a demo.
<div #container class="container">
<ul>
<li *ngFor="let i of items">{{i}}</li>
</ul>
</div>
<button (click)="container.scrollTop = 0">scroll to top</button>
这是一种简单的方法,可以平滑滚动到列表的顶部.它基于
Here is a simple method that scrolls smoothly to the top of the list. It is based on this answer by bryan60, and adapted to RxJS 6. You can try it in 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();
}
这篇关于如何在角度单击时将列表滚动到顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!