平滑滚动角度2

时间:2016-03-18 18:50:39

标签: scroll typescript angular smooth-scrolling

我无法获得平滑滚动服务以在角度2中工作。是否有任何平滑滚动服务或普通锚点滚动,这可能会有效,直到角度2团队获得$ anchorScroll angular2等效工作?

到目前为止,我刚试过:

在父div上设置* ngFor循环增量ID

[attr.id]="'point' + i"

在ID传递

的按钮上调用scrollto
<button 
     type="button" 
     class="btn btn-lg btn-default " 
     (click)="smoothScroll('point'+i)">
           Scroll to point
</button>

在相关组件中,我试图实现普通的js平滑滚动功能

smoothScroll(eID) {
        var startY = currentYPosition();
        var stopY = elmYPosition(eID);
        var distance = stopY > startY ? stopY - startY : startY - stopY;
        if (distance < 100) {
            scrollTo(0, stopY); return;
        }
        var speed = Math.round(distance / 100);
        if (speed >= 20) speed = 20;
        var step = Math.round(distance / 25);
        var leapY = stopY > startY ? startY + step : startY - step;
        var timer = 0;
        if (stopY > startY) {
            for (var i = startY; i < stopY; i += step) {
                setTimeout(this.win.scrollTo(0, leapY), timer * speed);
                leapY += step; if (leapY > stopY) leapY = stopY; timer++;
            } return;
        }
        for (var i = startY; i > stopY; i -= step) {
            setTimeout(this.win.scrollTo(0,leapY), timer * speed);
            leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
        }
    }
function currentYPosition() {
    // Firefox, Chrome, Opera, Safari
    if (self.pageYOffset) return self.pageYOffset;
    // Internet Explorer 6 - standards mode
    if (document.documentElement && document.documentElement.scrollTop)
        return document.documentElement.scrollTop;
    // Internet Explorer 6, 7 and 8
    if (document.body.scrollTop) return document.body.scrollTop;
    return 0;
}
function elmYPosition(eID) {
    var elm = document.getElementById(eID);
    var y = elm.offsetTop;
    var node = elm;
    while (node.offsetParent && node.offsetParent != document.body) {
        node = node.offsetParent;
        y += node.offsetTop;
    } return y;
}

我也试图访问来自窗口提供程序服务的this._win.scrollTo的窗口

import {Injectable, Provider} from 'angular2/core';
import {window} from 'angular2/src/facade/browser';
import {unimplemented} from 'angular2/src/facade/exceptions';

function _window(): Window {
  return window
}

export abstract class WINDOW {
  get nativeWindow(): Window {
    return unimplemented();
  }
}

class WindowRef_ extends WINDOW {
  constructor() {
    super();
  }
  get nativeWindow(): Window {
    return _window();
  }
}

export const WINDOW_PROVIDERS = [
  new Provider(WINDOW, { useClass: WindowRef_ }),
];

**编辑 --------------------- **

我将this.win.scrollTo更改为this.win.window.scrollTo现在我得到类似于angular1.x $ anchorscroll的效果,其中滚动是一个snappy而不是平滑过渡,但滚动是不顺利,我收到以下异常错误。

Exception error

更新

在发现angular2以不同的方式执行setTimeout之后,我不再收到该错误,但滚动仍然是瞬时的,而不是平滑的滚动。

我改变了

  setTimeout(this.win.scrollTo(0, leapY), timer * speed);

 setTimeout(() => this.win.scrollTo(0, leapY), timer * speed);

9 个答案:

答案 0 :(得分:31)

window对象中有一个名为scrollTo()的方法。 如果将行为设置为“平滑”,则页面将处理平滑滚动。 示例(滚动到页面顶部):

 window.scrollTo({ left: 0, top: 0, behavior: 'smooth' });

以后备为例:

    try 
    { 
     window.scrollTo({ left: 0, top: 0, behavior: 'smooth' });
     } catch (e) {
      window.scrollTo(0, 0);
      }

答案 1 :(得分:16)

好吧,稍微刮了一下头后,这是一个似乎正常的解决方案。

与之前相同,我在单击时声明了条件id和带有scrollTo函数调用的按钮。

现在,解决方案中只有两个文件是一个有助于返回文档窗口和模板组件的服务。从上面的状态窗口服务中没有任何改变,但为了得到一个好的答案,我将再次包括它。

window.service.ts:向https://gist.github.com/lokanx/cc022ee0b8999cd3b7f5喊出来帮助解决这个问题

import {Injectable, Provider} from 'angular2/core';
import {window} from 'angular2/src/facade/browser';
import {unimplemented} from 'angular2/src/facade/exceptions';

function _window(): Window {
  return window
}

export abstract class WINDOW {
  get nativeWindow(): Window {
    return unimplemented();
  }
}

class WindowRef_ extends WINDOW {
  constructor() {
    super();
  }
  get nativeWindow(): Window {
    return _window();
  }
}

export const WINDOW_PROVIDERS = [
  new Provider(WINDOW, { useClass: WindowRef_ }),
];

app.component.ts

import { bootstrap } from 'angular2/platform/browser';
import { Component } from 'angular2/core';
import {WINDOW, WINDOW_PROVIDERS} from './window.service';

@Component({
  selector: 'my-app',
  templateUrl: 'app.tpl.html',
  providers: [WINDOW_PROVIDERS]
})

class AppComponent {
    win: Window;
    private offSet: number;
    constructor(
        private _win: WINDOW) { 
        this.win = _win.nativeWindow;
    }
    title = 'Ultra Racing';
    things = new Array(200);

    scrollTo(yPoint: number, duration: number) {
        setTimeout(() => {
            this.win.window.scrollTo(0, yPoint)
        }, duration);
        return;
    }
    smoothScroll(eID) {
        var startY = currentYPosition();
        var stopY = elmYPosition(eID);
        var distance = stopY > startY ? stopY - startY : startY - stopY;
        if (distance < 100) {
            this.win.window.scrollTo(0, stopY); return;
        }
        var speed = Math.round(distance / 100);
        if (speed >= 20) speed = 20;
        var step = Math.round(distance / 100);
        var leapY = stopY > startY ? startY + step : startY - step;
        var timer = 0;
        if (stopY > startY) {
            for (var i = startY; i < stopY; i += step) {
                this.scrollTo(leapY, timer * speed);
                leapY += step; if (leapY > stopY) leapY = stopY; timer++;
            } return;
        }
        for (var i = startY; i > stopY; i -= step) {
            this.scrollTo(leapY, timer * speed);
            leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
        }
    }
}
function currentYPosition() {
    // Firefox, Chrome, Opera, Safari
    if (self.pageYOffset) return self.pageYOffset;
    // Internet Explorer 6 - standards mode
    if (document.documentElement && document.documentElement.scrollTop)
        return document.documentElement.scrollTop;
    // Internet Explorer 6, 7 and 8
    if (document.body.scrollTop) return document.body.scrollTop;
    return 0;
}
function elmYPosition(eID) {
    var elm = document.getElementById(eID);
    var y = elm.offsetTop;
    var node = elm;
    while (node.offsetParent && node.offsetParent != document.body) {
        node = node.offsetParent;
        y += node.offsetTop;
    } return y;
}

bootstrap(AppComponent)

我创建了一个plunk以显示此示例正常工作: Plunk Example

答案 2 :(得分:11)

实现这一目标的更简单方法是使用此polyfill: http://iamdustan.com/smoothscroll/

  1. 安装为: npm install smoothscroll-polyfill
  2. 将其导入polyfill.ts文件中: require('smoothscroll-polyfill')。polyfill();
  3. 现在您可以将scrollIntoView的行为选项用作:

    (document.querySelector('#'+ anchor))。scrollIntoView({behavior:'smooth'});

答案 3 :(得分:2)

如果你想要一个非常简单的锚点跳转,它在路由后和路由视图中有效,你也可以使用ng2-simple-page-scroll

<a simplePageScroll href="#myanchor">Go there</a>

或路线后:

<a simplePageScroll [routerLink]="['Home']" href="#myanchor">Go there</a>

它做了一个简单的即时跳转,但它确实有效。

答案 4 :(得分:2)

对于仍然在寻找顺畅滚动的人来说@ alex-j的回答对Angular 2.0来说非常有用 - 但我不得不将Window服务更改为: -

import { Injectable } from '@angular/core';

function _window() : any {
    // return the global native browser window object
    return window;
}

@Injectable()
export class WindowRef {
    get nativeWindow() : any {
        return _window();
    }
}

此博客的所有道具http://juristr.com/blog/2016/09/ng2-get-window-ref/ - 现在我可以随时随地拨打顺畅的滚动服务:)

答案 5 :(得分:2)

示例:

function goToElement(elemId){
 let element = window.getElementById(elemId);
 element.scrollIntoView({behavior: "smooth"});
}

答案 6 :(得分:1)

我使用此代码。

        var dis = distance  ;
        var interval = setInterval(() => {
            this.document.body.scrollTop = dis;
             dis=dis-5 ;
             if (dis<10){
                 clearInterval(interval);
             }
        }, 5);

答案 7 :(得分:0)

感谢接受的答案,我能够实现顺畅的“滚动到顶部”。滚动到顶部实际上比滚动到特定目标元素更容易,因为我们总是滚动到0位置。这是代码:

scrollTo(yPoint: number, duration: number) {
    setTimeout(() => {
        window.scrollTo(0, yPoint)
    }, duration);
    return;
}

smoothScrollToTop() {
    let startY = this.currentYPosition();
    let stopY = 0; // window top
    let distance = stopY > startY ? stopY - startY : startY - stopY;
    if (distance < 100) {
        window.scrollTo(0, stopY);
        return;
    }
    let speed = Math.round(distance / 100);
    let step = speed;
    speed = Math.max(9, speed); //min 9 otherwise it won't look smooth
    let leapY = stopY > startY ? startY + step : startY - step;
    let timer = 0;
    if (stopY > startY) {
        for (let i = startY; i < stopY; i += step) {
            // since setTimeout is asynchronous, the for-loop will will fire all scrolls
            // nearly simoultaniously. Therefore, we need to multiply the speed with
            // a counter which lets the scrolls start with a growing offset which lets the
            // setTimeout wait for a growing time till it scrolls there
            // that way, we prevent the window to scroll instantly to the target Yposition
            this.scrollTo(leapY, timer * speed);
            leapY += step; if (leapY > stopY) leapY = stopY; timer++;
        }
        return;
    } else {
        for (let i = startY; i > stopY; i -= step) {
            this.scrollTo(leapY, timer * speed);
            leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
        }
    }
}

currentYPosition() {
    // Firefox, Chrome, Opera, Safari
    if (self.pageYOffset) return self.pageYOffset;
    // Internet Explorer 6 - standards mode
    if (document.documentElement && document.documentElement.scrollTop)
        return document.documentElement.scrollTop;
    // Internet Explorer 6, 7 and 8
    if (document.body.scrollTop) return document.body.scrollTop;
    return 0;
}

如果需要,您可以在用户滚动时动态显示“滚动到顶部”按钮:

@HostListener('window:scroll', ['$event'])
onWindowScroll(event) {
    this.onScrollFadeInOutScrollToTopButton();
}

shouldShowScrollToTop: boolean = false;

onScrollFadeInOutScrollToTopButton() {
    this.shouldShowScrollToTop = (window.pageYOffset >= window.screen.height/2);
}

滚动到顶部按钮的HTML:

<div class="back-to-top">
<button *ngIf="shouldShowScrollToTop" [@fadeInOutTrigger]="animateButtonEntryState" class="mat-primary" md-fab (click)="smoothScrollToTop()">^</button>

如您所见,该按钮还具有动画触发器。您可以考虑使用按钮的图标,理想情况下,您的按钮应该具有position:fixed;样式。

答案 8 :(得分:-2)

还有另一种方法,可以考虑:使用jQuery。

也许它不如原生解决方案那么优雅,但非常简单且完美。

在index.html中,你必须将它添加到正文的末尾:

<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>

<script>
  $(document).on("click", "a[href*='#']:not([href='#'])", function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
          $('html, body').animate({
          scrollTop: target.offset().top - 100
          }, 1000);
          return false;
      }
    }
  });

</script>

现在您可以像这样使用简单的<a href("#section")>导航:

<a href="#section2">Link</a>

它也适用于路由:

<a class="btn" role="button" routerLink="/contact" fragment="contact_form">Contact us!</a>