简体   繁体   中英

How to scroll the page to the top when i am in missle of page or at end of page using angular2

I want my page to scroll top if it is in bottom on click of the button and if it is at the middle then also it must show icon to scroll top.

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

Here is an answer you are looking for:

App Component:

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>

Style:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM