angular - 使用带有Angular 2CLI的平滑滚动Polyfill

谁可以指导我如何使用Polyfill与Angular 2CLI 的平滑滚动。

我尝试在polyfills.ts下面添加,但是,它在require时抛出错误,


require('smoothscroll-polyfill').polyfill();



然后我尝试添加


import 'smoothscroll-polyfill';



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


ERROR TypeError: Failed to execute 'scroll' on 'Window': No function was found that matched the signature provided.



时间:

你需要安装polyfill和@types

  • yarn add smoothscroll-polyfillnpm install smoothscroll-polyfill
  • yarn add @types/smoothscroll-polyfill 或者 npm install @types/smoothscroll-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();


 }



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


 clickAnyThing(event:any){


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


 }



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


import smoothscroll from 'smoothscroll-polyfill/dist/smoothscroll';


smoothscroll.polyfill();



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


your_element.scrollIntoView({ behavior: 'smooth' });



以下是Angular 2/4解决方案:

安装smoothscroll-polyfill -,npm install smoothscroll-polyfill 。

然后添加到你的src/polyfills.js文件:


import smoothscroll from 'smoothscroll-polyfill/dist/smoothscroll.js';


smoothscroll.polyfill();



如果你正在使用Angular cli

首先安装软件包:

npm install smoothscroll-polyfill

然后在apps.scripts数组下面将以下内容添加到angular-cli.json :

"../node_modules/smoothscroll-polyfill/src/smoothscroll.js"

然后尝试一些类似的东西:

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

它应该能工作。

如果你正在使用typeScript,那么你应该安装,

npm install smoothscroll-polyfill @types/smoothscroll-polyfill

或者

yarn add smoothscroll-polyfill @types/smoothscroll-polyfill /

然后就可以像下面那样使用


 import * as smoothscroll from "smoothscroll-polyfill";


 smoothscroll.polyfill();




或者,仅当需要polyfill时,才可以包含它,如果你使用web pack,parcel 或任何支持动态导入的构建系统,你可以尝试以下内容。


 if (!'scrollBehavior' in document.documentElement.style) {


 // Wait until the Polyfills are loaded


 Promise.all([


 import('smoothscroll-polyfill'),


 import('smoothscroll-anchor-polyfill')


 ])


 // then use the modules however you want


 .then(([smoothscrollPolyfill, smoothscrollAnchorPolyfill]) => {


 // (Unlike this package, smoothscroll-polyfill needs to be actively invoked: )


 smoothscroll.polyfill();


 });


 }




#选项1

它可以直接包含在index.html中它将立即运行不需要使用smoothscroll.polyfill();调用


<script src="https://unpkg.com/smoothscroll-polyfill@0.4.3/dist/smoothscroll.min.js"></script>



#option 2

npm install smoothscroll-polyfill --save

包括在src/polyfills.ts

import 'smoothscroll-polyfill';

或者将它添加到.angular-cli.json中的scripts应该可以工作。

在组件中导入:


import { polyfill } from "smoothscroll-polyfill"



polyfill()



  • #使用:

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

...