javascript - 当我在页面中间或页面末尾时如何使用 Angular 2 将页面滚动到顶部

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

最佳答案

这是您正在寻找的答案:

应用组件:

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

关于javascript - 当我在页面中间或页面末尾时如何使用 Angular 2 将页面滚动到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49750018/

相关文章:

c# - 按页分类的表格

php - 如何使用PHP显示HTML源代码

html - 如何将我的 div 放在容器的底部?

html - Dreamweaver中正则表达式注释掉css

javascript - 如何使用reduce JavaScript 添加同一周的计数?

javascript - 有人发现我的重置功能有错误吗?

javascript indexOf - 列表/数组中的完全匹配

javascript - 通过单击按钮而不是单击行来处理折叠的 html 表格

javascript - 跳转到屏幕外元素时防止 Chrome 中的页面跳转

javascript - 从第二个函数调用中提交取消表单提交