window scroll top
window.pageYOffsetとdocument.documentElement.scrollTopは、どちらの場合も同じ結果を返します。window.pageYOffsetはIE 9以下ではサポートされていません。
app.component.ts
import { Component, HostListener, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
isShow: boolean;
topPosToStartShowing = 100;
@HostListener('window:scroll')
checkScroll() {
const scrollPosition = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
console.log('[scroll]', scrollPosition);
if (scrollPosition >= this.topPosToStartShowing) {
this.isShow = true;
} else {
this.isShow = false;
}
}
gotoTop() {
window.scroll({
top: 0,
left: 10,
behavior: 'smooth'
});
}
}
app.component.html
<style>
p {
font-family: Lato;
}
button {
position: fixed;
bottom: 5px;
right: 5px;
font-size: 20px;
text-align: center;
border-radius: 5px;
outline: none;
}
</style>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Minus, repudiandae quia. Veniam amet fuga, eveniet velit ipsa repudiandae nemo? Sit dolorem itaque laudantium dignissimos, rerum maiores nihil ad voluptates nostrum.
</p>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Minus, repudiandae quia. Veniam amet fuga, eveniet velit ipsa repudiandae nemo? Sit dolorem itaque laudantium dignissimos, rerum maiores nihil ad voluptates nostrum.
</p>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Minus, repudiandae quia. Veniam amet fuga, eveniet velit ipsa repudiandae nemo? Sit dolorem itaque laudantium dignissimos, rerum maiores nihil ad voluptates nostrum.
</p>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Minus, repudiandae quia. Veniam amet fuga, eveniet velit ipsa repudiandae nemo? Sit dolorem itaque laudantium dignissimos, rerum maiores nihil ad voluptates nostrum.
</p>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Minus, repudiandae quia. Veniam amet fuga, eveniet velit ipsa repudiandae nemo? Sit dolorem itaque laudantium dignissimos, rerum maiores nihil ad voluptates nostrum.
</p>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Minus, repudiandae quia. Veniam amet fuga, eveniet velit ipsa repudiandae nemo? Sit dolorem itaque laudantium dignissimos, rerum maiores nihil ad voluptates nostrum.
</p>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Minus, repudiandae quia. Veniam amet fuga, eveniet velit ipsa repudiandae nemo? Sit dolorem itaque laudantium dignissimos, rerum maiores nihil ad voluptates nostrum.
</p>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Minus, repudiandae quia. Veniam amet fuga, eveniet velit ipsa repudiandae nemo? Sit dolorem itaque laudantium dignissimos, rerum maiores nihil ad voluptates nostrum.
</p>
<button *ngIf="isShow" (click)="gotoTop()">👆</button>
RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'enabled' })