Vin*_*Ram 15 javascript typescript angular2-routing angular
我正在开发angular2 web应用程序,我需要以下帮助.我的页面由多个组件组成.我想在用户点击按钮时滚动页面顶部.我试过
document.body.scrollTop = 0;但这不适用于Chrome.我试过document.documentElement.scrollTop = 0; window.scrollTo(0,0); 但没有工作
小智 19
像这样导入,
import { Inject} from "@angular/core";
import { DOCUMENT } from '@angular/platform-browser';
Run Code Online (Sandbox Code Playgroud)
在你的构造函数中添加这个,
constructor(@Inject(DOCUMENT) private document: Document) { }
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样设置滚动,
this.document.body.scrollTop = 0;
Run Code Online (Sandbox Code Playgroud)
小智 5
我使用数据绑定解决了角度滚动问题:
<div class="container" [scrollTop]="scrollTop"> ... </div>
Run Code Online (Sandbox Code Playgroud)
与样式:
.container {
height: 100%;
scroll: auto;
position: relative;
}
Run Code Online (Sandbox Code Playgroud)
我建议为此编写指令。确保将其导入到您正在使用的模块中。
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[scrollToTop]'
})
export class ScrollToTopDirective {
@HostListener('click')
public onClick() {
if (window && window.pageYOffset) {
window.scroll(0, 0);
}
}
}
Run Code Online (Sandbox Code Playgroud)
并像下面一样使用它
<button scrollToTop>Scroll to Top</button>
Run Code Online (Sandbox Code Playgroud)
还可以考虑根据 Angular 最佳实践将前缀添加到指令中。
https://angular.io/guide/styleguide#directive-custom-prefix