Javascript 在 angular2 中滚动顶部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43692138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:06:43  来源:igfitidea点击:

Scroll Top in angular2

javascriptangulartypescriptangular2-routing

提问by Vinodh Ram

I am working on angular2 web application where I need help on the following. My page consists of multiple components. I want to scroll top of the page when user clicks a button. I tried document.body.scrollTop = 0;but this is not working in Chrome. I Tried document.documentElement.scrollTop=0;window.scrollTo(0, 0); but not working

我正在开发 angular2 Web 应用程序,我需要以下方面的帮助。我的页面由多个组件组成。当用户单击按钮时,我想滚动页面顶部。我试过了, document.body.scrollTop = 0;但这在 Chrome 中不起作用。我试过 document.documentElement.scrollTop=0;window.scrollTo(0, 0); 但不工作

回答by jaseelmp

import like this,

像这样导入,

import { Inject} from "@angular/core";
import { DOCUMENT } from '@angular/platform-browser';

In your constructor add this,

在你的构造函数中添加这个,

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

Then you can set the scroll anywhere like this,

然后你可以像这样在任何地方设置滚动,

this.document.body.scrollTop = 0;

回答by JanP

Just use:

只需使用:

window.scroll(0, 0);

回答by Julien Pilet

I solved my angular scrolling problem using data binding:

我使用数据绑定解决了我的角度滚动问题:

<div class="container" [scrollTop]="scrollTop"> ... </div>

with the styles:

与样式:

.container {
  height: 100%;
  scroll: auto;
  position: relative;
}

回答by Vinodh Ram

In app.component.ts

在 app.component.ts

const mainDiv = document.getElementById('mainDIV');
mainDiv.scrollTop = 0;

In app.component.html

在 app.component.html

<div id="mainDIV" style="height: 100vh;overflow: auto;">
    <app-header></app-header>
    <router-outlet></router-outlet>
    <app-footer></app-footer>
</div>

回答by Viktor Soroka

I propose to write directive for that. Make sure to import it in the module you are using.

我建议为此编写指令。确保将其导入您正在使用的模块中。

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[scrollToTop]'
})
export class ScrollToTopDirective {
  @HostListener('click')
  public onClick() {
    if (window && window.pageYOffset) {
      window.scroll(0, 0);
    }
  }
}

and use it like below

并像下面一样使用它

<button scrollToTop>Scroll to Top</button>

Consider also to add the prefix to the directive in compliance with Angular best practices.

还考虑将前缀添加到符合 Angular 最佳实践的指令。

https://angular.io/guide/styleguide#directive-custom-prefix

https://angular.io/guide/styleguide#directive-custom-prefix

回答by Tapas Garai

Please use below code. For my case

请使用下面的代码。对于我的情况

this.document.body.scrollTop = 0

not working but

不工作但是

this.document.documentElement.scrollTop = 0

working. So may be some browser dependency.

在职的。所以可能是一些浏览器依赖。

import { Inject} from "@angular/core";
import { DOCUMENT } from '@angular/platform-browser';

constructor(@Inject(DOCUMENT) private document: Document) { }
this.document.documentElement.scrollTop = 0;

回答by Rajesh Valluru

html code :

html代码:

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

css code:

css代码:

.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:

ts 代码:

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));
          }
      })();
  }

}

回答by anlijudavid

Inject this argument into your constructor: @Inject(DOCUMENT) private document: Document

将此参数注入您的构造函数: @Inject(DOCUMENT) private document: Document

Then, call scrollIntoViewfunction:

然后,调用scrollIntoView函数:

this.document.body.scrollIntoView({
   block: 'start',
   behavior: 'smooth'
});

Ready!! :)

准备好!!:)

回答by anja

If it is not window scroll, but just div with his own scroll, this should work:

如果它不是窗口滚动,而只是带有他自己的滚动条的 div,这应该可以工作:

Gloabal service WindowRef:

全球服务WindowRef:

import { Injectable } from '@angular/core';

function _window(): any {
  // return the global native browser window object
  return window;
}

@Injectable()
export class WindowRef {
  get nativeWindow(): any {
    return _window().document;
  }
}

Add it to constructor:

将其添加到构造函数:

constructor(private winRef: WindowRef) {}

And in the code, where you want to put it just add this line:

在代码中,您想要放置它的地方只需添加以下行:

this.winRef.nativeWindow.getElementsByClass('nameOfClass')[0].scroll(0, 0);

Of course you can also use other selectors like: getElementByTagName, getElementById, getElementByName ...

当然,您也可以使用其他选择器,例如:getElementByTagName、getElementById、getElementByName ...