文章内容

2020/7/16 10:05:55,作 者: 黄兵

Angular滚动到顶部示例代码

html code:

<div class="scroll-to-top" [ngClass]="{'show-scroll': navIsFixed}">
<button (click)="scrollToTop()">
Top
</button>
</div>

css code:

.scroll-to-top {
position: fixed;
bottom: 15px;
right: 15px;
opacity: 0;
transition: all .2s ease-in-out;
}

.show-scroll {
opacity: 1;
transition: all .2s ease-in-out;
}

ts code:

import {Component, OnInit, Inject, HostListener} from '@angular/core';
import {DOCUMENT} from '@angular/platform-browser';
import {BrowserModule} from '@angular/platform-browser';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Hard Hitter@Cool';
navIsFixed: boolean;

constructor(@Inject(DOCUMENT) private document: Document) {

}

@HostListener('window:scroll', [])
onWindowScroll() {
if (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop > 100) {
this.navIsFixed = true;
} else if (this.navIsFixed && window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop < 10) {
this.navIsFixed = false;
}
}

scrollToTop() {
(function smoothscroll() {
var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
if (currentScroll > 0) {
window.requestAnimationFrame(smoothscroll);
window.scrollTo(0, currentScroll - (currentScroll / 5));
}
})();
}
}

这里面的有一个重点window.requestAnimationFrame()需要着重讲一下:

window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行

当你准备更新动画时你应该调用此方法。这将使浏览器在下一次重绘之前调用你传入给该方法的动画函数(即你的回调函数)。回调函数执行次数通常是每秒60次,但在大多数遵循W3C建议的浏览器中,回调函数执行次数通常与浏览器屏幕刷新次数相匹配。为了提高性能和电池寿命,因此在大多数浏览器里,当requestAnimationFrame() 运行在后台标签页或者隐藏的<iframe> 里时,requestAnimationFrame() 会被暂停调用以提升性能和电池寿命。

可以看到这个函数如果是在手机上运行,可以节省一部分电量。


参考资料:

1、Scroll Top in angular2

2、window.requestAnimationFrame

分享到:

发表评论

评论列表