在Angular中使用Parallax.js会引发错误“无法读取null的'getAttribute'属性”

时间:2019-07-07 13:34:33

标签: angular parallax.js

我正在使用parallax.js(https://github.com/wagerfield/parallax)来实现鼠标悬停视差效果。我通过cdn和script标签将脚本添加到我的angular应用程序中。 在控制台中,它显示此错误:

 Uncaught TypeError: Cannot read property 'getAttribute' of null
    at Object.data (parallax.js:23)
    at new t (parallax.js:161)
    at (index):36

我试图通过npm安装该库并将其导入ts文件,但这没用。

这是我的index.html:

<body>
  <app-root></app-root>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/parallax/3.1.0/parallax.min.js"></script>
  <script type="text/javascript">
  var parallaxInstance = new Parallax(document.getElementById('scene'));
  </script>
</body> 

我在其中使用它的组件:

 <ul class="background-video" id="scene">

  <li class="layer" data-depth="0.7"><img src="/assets/parallax/ebene1.png" alt="" srcset=""></li>
  <li class="layer" data-depth="0.5"><img src="/assets/parallax/ebene2.png" alt="" srcset=""></li>
  <li class="layer" data-depth="0.3"><img src="/assets/parallax/ebene3.png" alt="" srcset=""></li>

 </ul>

1 个答案:

答案 0 :(得分:2)

由于JS异步特性,某些事情可能会以错误的顺序发生,因为我能够在此example中运行它(由于依赖问题,它无法在stackblitz上运行,而是在您的comp上本地运行有效)。

首先从您的html示例中删除除根节点以外的节点,并在其中添加视差组件,如下所示:

index.html:

 <body>
      <app-root></app-root>
 </body>

app.html:

<parallax></parallax>

由于在组件中使用了它,因此在ng-app中,应像在angular.json中那样,通过将其注入应用程序捆绑包来初始化实际组件中的lib:

"options": {
    "scripts": [
                  "./node_modules/parallax-js/dist/parallax.min.js"
               ]
}

,然后将其导入/ts.ts文件中,如下所示:

import Parallax from 'parallax-js'
import { Component,AfterContentInit } from '@angular/core';

export class ParallaxComponent implements AfterContentInit {

  constructor() { }

  ngAfterContentInit() {

    const scene = document.getElementById('scene');
    const parallaxInstance = new Parallax(scene, {
      relativeInput: true
    });

  }

}