当我在页面的页面或使用angular2的页面末尾时,如何将页面滚动到顶部

时间:2018-04-10 09:25:26

标签: javascript html css

如果点击按钮,我希望我的页面在顶部滚动,如果它在中间,那么它也必须显示图标以滚动顶部。

HTML:

<footer>
 <div class="container">
   <div class="row containerDiv">
   </div>
 </div>
 <hr />
 <button class="scrollToTop" (click)="goTop()"><i class="fa fa-arrow-up"></i></button>
 <div class="container">
   <div class="row">
   </div>
 </div>
 <hr />
</footer>

的CSS:

.scrollToTop {
 color: #fafafa;
   float: right;
   margin-right: 2%;
   box-shadow: 0 1px 1.5px 0 rgba(0,0,0,.12), 0 1px 1px 0 rgba(0,0,0,.24);
   width: 50px;
   height: 50px;
   border-radius: 100px;
   border: none;
   outline: none;
   background: #8350ec;
}

1 个答案:

答案 0 :(得分:2)

以下是您正在寻找的答案:

应用组件:

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

@Component({
    selector: 'app',
    template: require('./app.component.html'),
    styles: [require('./app.component.css')]
})
export class AppComponent implements OnInit {
    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));
            }
        })();
    }

    ngOnInit(): void {
    }
}

<强> HTML:

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

<强>样式:

.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;
}