【问题标题】:Scroll Top in angular2在 angular2 中滚动顶部
【发布时间】:2017-09-27 06:38:32
【问题描述】:

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

【问题讨论】:

  • document.body.scrollTop = 0; 应该可以工作,无论如何错误是什么?
  • 它没有给出错误。但它不适用于 chrome
  • 你能在 plunker 上创建你的问题吗?
  • 你能至少告诉我们你是如何绑定事件的,你的页面有多长?
  • let ele = document.querySelector('.informationBdrCmpt') as HTMLElement; ele.scrollTop(0);不管用。任何帮助。 ......收到错误为 [ts] 无法调用类型缺少调用签名的表达式。类型“号码”没有兼容的调用签名。

标签: javascript angular typescript angular2-routing


【解决方案1】:

像这样导入,

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

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

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

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

this.document.body.scrollTop = 0;

【讨论】:

  • 从@angular/platform-b​​rowser 导入似乎已被弃用,建议改为从@angular/common 导入。 link
  • 这似乎不起作用。使用 Angular 4/CLI 没有错误,只是没有响应。
  • 对我来说,它确实在 Angular 2 中工作(即使没有注入 DOCUMENT)。刚刚更新到 Angular 5.0.3 并尝试了上述解决方案,但对我来说它不起作用。
  • 编辑:刚刚意识到这与 Chrome 的某些更新有关。它在 Safari 中运行良好,但在 Chrome 中无法运行,无论是在 Angular2(它之前可以运行的地方)还是在 Angular 5 中。
  • 如果您使用的是 Angular CLI,请使用第二个答案,它对我有用
【解决方案2】:

在 app.component.ts 中

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

在 app.component.html 中

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

【讨论】:

    【解决方案3】:

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

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

    样式:

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

    【讨论】:

    • 这是我的首选答案,但请记住,如果 scrollTop 的值在组件中没有改变,您将不会看到任何事情发生。例如,如果您在组件中将默认值设置为 0,滚动页面,然后在单击按钮或其他操作后将其设置为零。
    【解决方案4】:

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

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

    并像下面这样使用它

    <button scrollToTop>Scroll to Top</button>
    

    还要考虑为指令添加前缀以符合 Angular 最佳实践。

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

    【讨论】:

    • 你说得对,不需要。删除它。谢谢。
    • 很好)谢谢。我认为这样确保代码 sn-ps 的质量是件好事。在 IDE 中这样的事情很快就会被发现,所以我需要习惯在这里发现这样的事情。
    【解决方案5】:

    只需使用:

    window.scroll(0, 0);
    

    【讨论】:

      【解决方案6】:

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

      全局服务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;
        }
      }
      

      将其添加到构造函数中:

      constructor(private winRef: WindowRef) {}
      

      在代码中,你想把它放在哪里,只需添加这一行:

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

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

      【讨论】:

        【解决方案7】:

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

        this.document.body.scrollTop = 0
        

        不工作,但是

        this.document.documentElement.scrollTop = 0
        

        工作。所以可能是一些浏览器依赖。

        import { Inject} from "@angular/core";
        import { DOCUMENT } from '@angular/platform-browser';
        
        constructor(@Inject(DOCUMENT) private document: Document) { }
        this.document.documentElement.scrollTop = 0;
        

        【讨论】:

          【解决方案8】:

          html代码:

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

          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 代码:

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

          【讨论】:

            【解决方案9】:

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

            然后,调用scrollIntoView函数:

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

            准备好了!! :)

            【讨论】:

              猜你喜欢
              • 2019-01-27
              • 1970-01-01
              • 2017-02-17
              • 2013-10-09
              • 1970-01-01
              • 2019-02-23
              • 2021-10-02
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多