[英]how to scroll the list to top on button click in angular?
你能告訴我如何在 angular 中單擊按鈕時將列表滾動到頂部嗎? 我這樣試過
scrollToTop(el){
el.scrollIntoView();
}
<button (click)="scrollToTop(target)">scroll to top</button>
它將列表滾動到頂部。但它隱藏了我的地址header
addressbar
認為這不是一個好的解決方案。任何人都有任何其他好的解決方案
這是我的代碼https://stackblitz.com/edit/angular-f9qxqh?file=src%2Fapp%2Fapp.component.html
您可以通過將容器的scrollTop
屬性設置為零來滾動到列表的頂部。 有關演示,請參見此堆疊閃電戰 。
<div #container class="container">
<ul>
<li *ngFor="let i of items">{{i}}</li>
</ul>
</div>
<button (click)="container.scrollTop = 0">scroll to top</button>
這是一種可以輕松滾動到列表頂部的簡單方法。 它基於bryan60的 答案 ,並適用於RxJS6。您可以在此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();
}
您將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();
}
Typescript
ngOnInit(): void {
const scroller = document.querySelector(".wrapper");
scroller?.addEventListener("scroll", (event) => {
if(scroller?.scrollTop > 300){
this.windowScrolled = true;
} else{
this.windowScrolled = false;
}
});
}
scrollToTop(): void {
document.getElementsByClassName('wrapper')[0].scrollTo(0,0);
}
HTML
<p>
<a *ngIf="windowScrolled" class="topButton" (click)="scrollToTop()" title="Go to top">
<i class="pi pi-angle-double-up"><i class="pi pi-angle-double-up"></i></i>
</a>
SCSS
.topButton{
position: fixed;
transition: all 0.2s ease-in-out;
z-index: 1030;
right: 30px;
bottom: 50px;
font-weight: bolder;
cursor: pointer;
background-color: #002266;
color: white;
width: 23px;
height: 34px;
text-align: center;
vertical-align: middle;
border-radius: 15px;
padding: 3px;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.