Using Smooth Scroll Polyfill with Angular 2 CLI
任何人都可以指导如何在Angular 2 CLI中使用Smooth Scroll Polyfill。
我尝试将以下内容添加到polyfills.ts中,但在工作要求时抛出错误
1 | require('smoothscroll-polyfill').polyfill(); |
然后我尝试添加
1 | import 'smoothscroll-polyfill'; |
尽管在构建过程中没有引发任何错误,但是当我在浏览器中运行项目时,它在控制台上显示以下错误:
1 | ERROR TypeError: Failed to execute 'scroll' on 'Window': No function was found that matched the signature provided. |
您需要安装polyfill和@types
因此,在您的代码中,应在组件或服务中初始化您希望使用的Polyfill:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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(); } |
您可以在组件中使用,例如:
1 2 3 | clickAnyThing(event:any){ window.scroll({ top: 0, left: 0, behavior: 'smooth' }); } |
这里是Angular 2/4解决方案:
安装smoothscroll-polyfill-
然后将其添加到您的src / polyfills.ts文件中:
1 2 | import smoothscroll from 'smoothscroll-polyfill/dist/smoothscroll.js'; smoothscroll.polyfill(); |
这是我在
1 2 | import smoothscroll from 'smoothscroll-polyfill/dist/smoothscroll'; smoothscroll.polyfill(); |
然后您可以像这样使用它:
1 | your_element.scrollIntoView({ behavior: 'smooth' }); |
如果使用angularcli
首先安装软件包:
然后将以下内容添加到apps.scripts数组下的angular-cli.json中:
然后尝试类似的操作:
应该可以。
如果将它与Typescript一起使用,则应安装
或
然后您可以像下面这样使用它
1 2 | import * as smoothscroll from"smoothscroll-polyfill"; smoothscroll.polyfill(); |
或者,
您只能在需要时才加入polyfill。如果您使用的是webpack,parcel或任何其他支持动态导入的构建系统,则可以尝试以下操作。
1 2 3 4 5 6 7 8 9 10 11 12 | 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
它可以直接包含在
调用
1 | <script src="https://unpkg.com/[email protected]/dist/smoothscroll.min.js"> |
#选项2
包括在
中
或将其添加到
导入组件:
1 2 3 | import { polyfill } from"smoothscroll-polyfill" polyfill() |
- #利用:
- CodeSandbox
-
在两种情况下,脚本都将检测该规范是否受本机支持,并仅在必要时采取措施。
-
平滑滚动行为polyfill文档
- MDN:滚动行为浏览器兼容性
- 对于不支持该代码的浏览器,该代码需要requestAnimationFrame polyfill。