Angular 2显示并隐藏滚动按钮

时间:2017-04-07 12:05:25

标签: html angular typescript

当我第一次向下滚动时,我有一个显示在右上角的按钮。我在页面上向上滚动后想让按钮消失。 我怎样才能做到这一点? 到目前为止,我的打字稿功能跟踪($ event:any){}看起来像这样:

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


@Component({
    host: {'(window:scroll)': 'track($event)'}
})


export class DirectSearchComponent{
    showScrollButton:boolean=false;
    beginY: any;


constructor() {}

 track($event:any) {
    console.debug("Scroll Event", $event);
    if (this.beginY == undefined || this.beginY != null) {
        if (this.beginY > $event.scrollY) {
            this.showScrollButton = false;
        }
        else {
            this.showScrollButton = true;
        }
    }
    else {
        this.beginY = $event.scrollY;
        this.showScrollButton = true;
    }    
  }
 }

按钮的html代码如下所示:

  <a href="#" class="scrollup">
       <button *ngIf="showScrollButton"  
           type="button" class="btn btn-primary btn-block pull-right" 
                   style="position: fixed; bottom: 10px; right: 51px; 
                           width:3%; overflow:auto;">
                <i class="glyphicon glyphicon-chevron-up" ></i>
       </button>
     </a>

提前致谢!

1 个答案:

答案 0 :(得分:0)

看起来this.beginY未正确初始化。

导入NgOnInit并在NgOnInit方法中设置...

this.beginY = document.documentElement.scrollTop || document.body.scrollTop;

这应该正确地将您的变量初始化为初始页面滚动值。

相关问题