【问题标题】:set the scroll to top using CSS in Angular4 app在 Angular4 应用程序中使用 CSS 将滚动设置为顶部
【发布时间】:2018-03-07 04:02:11
【问题描述】:

在我的 Angular4 应用程序中,当我向下滚动某个列表并单击列表项以查看另一条路线上的详细信息时,需要向上滚动才能转到页面顶部。

我找到了一些使用 JQuery 将滚动设置为顶部的答案。但是是否可以仅使用 CSS(SASS 可能)将滚动设置为顶部?

【问题讨论】:

    标签: css angular scroll


    【解决方案1】:

    这是仅使用基于 css 的平滑滚动的快速示例。这是另一个SO thread,有更多答案。

    希望这会有所帮助。

    html {
      scroll-behavior: smooth
    }
    
    a {
      display: block;
      background: #fff;
      padding: 4px;
    }
    
    div {
      height: 1000px;
      width: 200px;
      padding: 4px;
    }
    
    #red {
      background: red;
    }
    
    #blue {
      background: blue;
    }
    
    #green {
      background: green;
    }
    
    #yellow {
      background: yellow;
    }
    <a name="top"></a>
    
    <a href="#red">Red</a>
    <a href="#blue">Blue</a>
    <a href="#green">Green</a>
    <a href="#yellow">Yellow</a>
    
    <div id="red"><a href="#top">Top</a></div>
    <div id="blue"><a href="#top">Top</a></div>
    <div id="green"><a href="#top">Top</a></div>
    <div id="yellow"><a href="#top">Top</a></div>

    【讨论】:

      【解决方案2】:

      试试这个,没有任何CSS。在您的应用程序组件(引导程序)中订阅路由器并检查事件是 NavigationEnd 的实例,然后将 scoll 窗口移至顶部

      import {Component, ElementRef, Inject} from '@angular/core';
      import {NavigationEnd, Router} from '@angular/router';
      
      
      @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
      })
      
      export class AppComponent {
      elementRef: ElementRef;
      
      constructor(@Inject(ElementRef) elementRef: ElementRef,
                private router: Router) {
      this.elementRef = elementRef;
      router.events.subscribe((myEvent) => {
        if (myEvent instanceof NavigationEnd) {
          window.scrollTo(0, 0);
        }
       });
      }
      }
      

      这里正在工作:https://plnkr.co/edit/IyO1Cp?p=preview

      【讨论】:

        猜你喜欢
        • 2017-12-02
        • 2018-07-05
        • 1970-01-01
        • 2011-03-12
        • 1970-01-01
        • 2020-01-20
        • 1970-01-01
        • 1970-01-01
        • 2020-08-27
        相关资源
        最近更新 更多