代码之家  ›  专栏  ›  技术社区  ›  naveen

如何滚动列表到顶部按钮按角度?

  •  1
  • naveen  · 技术社区  · 7 年前

    你能告诉我如何滚动列表到顶部按钮按角度吗? 我这样试过

     scrollToTop(el){
        el.scrollIntoView();
      }
    
      <button (click)="scrollToTop(target)">scroll to top</button>
    

    它将列表滚动到顶部。但是它隐藏了我的 addressbar 然后用户无法看到 header 我认为这不是个好办法。任何人都有其他好办法

    这是我的密码 https://stackblitz.com/edit/angular-f9qxqh?file=src%2Fapp%2Fapp.component.html

    2 回复  |  直到 7 年前
        1
  •  2
  •   ConnorsFan    7 年前

    您可以通过设置 scrollTop 容器的属性设置为零。见 this stackblitz 为了演示。

    <div #container class="container">
      <ul>
        <li *ngFor="let i of items">{{i}}</li>
      </ul>
    </div>
    
    <button (click)="container.scrollTop = 0">scroll to top</button>
    

    这里有一个简单的方法,可以平滑地滚动到列表的顶部。它基于 this answer 通过 bryan60 ,并适应RXJS6。你可以试试 this stackblitz 是的。

    <button (click)="scrollToTop(container)">scroll to top</button>
    
    import { interval as observableInterval } from "rxjs";
    import { takeWhile, scan, tap } from "rxjs/operators";
    ...
    
    scrollToTop(el) {
      const duration = 600;
      const interval = 5;
      const move = el.scrollTop * interval / duration;
      observableInterval(interval).pipe(
        scan((acc, curr) => acc - move, el.scrollTop),
        tap(position => el.scrollTop = position),
        takeWhile(val => val > 0)).subscribe();
    }
    
        2
  •  2
  •   Jagjeet Singh    7 年前

    你添加 scroll 到你的容器,所以它在容器上工作,而不是在 ul

    app.component.html软件

    <div class="container" #container>
      <ul #target>
        <li *ngFor="let i of items">{{i}}</li>
      </ul>
    </div>
    <button (click)="scrollToTop(container)">scroll to top</button>
    

    应用组件

    scrollToTop(el) {
     el.scrollTop = 0;          
    }
    

    为了 平滑滚动 ,使用此:

    scrollToTop(el) {
        var to = 0;
        var duration = 1000;
        var start = el.scrollTop,
            change = to - start,
            currentTime = 0,
            increment = 20;
    
        var easeInOutQuad = function(t, b, c, d) {
            t /= d / 2;
            if (t < 1) 
                return c / 2 * t * t + b;
            t--;
            return -c / 2 * (t * (t - 2) - 1) + b;
        }
    
        var animateScroll = function() {        
            currentTime += increment;
            var val = easeInOutQuad(currentTime, start, change, duration);
    
            el.scrollTop = val;
            if(currentTime < duration) {
                setTimeout(animateScroll, increment);
            }
        }
        animateScroll();    
    }
    
    推荐文章