使用带有Angular 2 CLI的Smooth Scroll Polyfill

Nav*_*med 3 angular-cli angular

任何人都可以指导如何使用Smooth Scroll Polyfill与Angular 2 CLI.

我尝试在polyfills.ts下面添加,但它会在工作需要时抛出错误

require('smoothscroll-polyfill').polyfill();
Run Code Online (Sandbox Code Playgroud)

然后我尝试添加

import 'smoothscroll-polyfill';
Run Code Online (Sandbox Code Playgroud)

虽然它在构建期间没有抛出任何错误,但是当我在浏览器中运行项目时,它在控制台上显示以下错误:

ERROR TypeError: Failed to execute 'scroll' on 'Window': No function was found that matched the signature provided.
Run Code Online (Sandbox Code Playgroud)

小智 5

这是Angular 2/4解决方案:

安装smoothscroll-填充工具 - npm install smoothscroll-polyfill

然后添加到您的src / polyfills.ts文件中:

import smoothscroll from 'smoothscroll-polyfill/dist/smoothscroll.js';
smoothscroll.polyfill();
Run Code Online (Sandbox Code Playgroud)


cab*_*rog 5

您需要安装polyfill和@types

  1. yarn add smoothscroll-polyfill 要么 npm install smoothscroll-polyfill
  2. yarn add @types/smoothscroll-polyfill 要么 npm install @types/smoothscroll-polyfill

因此,在您的代码中,您应该在组件或服务中初始化您希望使用此polyfill的polyfill:

import * as smoothscroll from "smoothscroll-polyfill";

@Component({
  selector: 'app-my-demo',
  templateUrl: './app-my-demo.html',
  styleUrls: ['./app-my-demo.css']
})
export MyClass my implements OnInit {

  constructor(
  ) {
    smoothscroll.polyfill();
   }
Run Code Online (Sandbox Code Playgroud)

您可以在组件中使用,例如:

  clickAnyThing(event:any){
    window.scroll({ top: 0, left: 0, behavior: 'smooth' });
  }
Run Code Online (Sandbox Code Playgroud)


Kev*_*rge 5

这是我在我的polyfills.ts文件中设置它的方式:

import smoothscroll from 'smoothscroll-polyfill/dist/smoothscroll';
smoothscroll.polyfill();
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

your_element.scrollIntoView({ behavior: 'smooth' });
Run Code Online (Sandbox Code Playgroud)