未捕获的TypeError:无法读取null的属性“ setAttribute”(控制台错误)

时间:2019-08-09 21:11:30

标签: javascript parallax

我尝试创建基本的视差背景,该代码可以正常工作,但是我遇到了无法摆脱的控制台错误。

未捕获的TypeError:无法读取null的属性“ setAttribute”

以下是一个指向示例的代码penn的链接:

https://codepen.io/bruno-gomes/pen/rXqOaK?editors=1010

HTML:

<div class="hero" id="parallax-1"></div>
<div class="content"> </div>

CSS:

.hero {
  height: 550px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #eee;
  padding: 60px 0 70px;
  background-image: url("http://piersrueb.com/sample/sample-3.jpg");
}

.content {
  height: 4000px;
}

JS:

window.onload = function() {

   const parallax = (id, modifier) => {
   const paraId = document.querySelector(id);

       paraId.setAttribute('style', 'background-repeat: no-repeat; background-attachment: fixed; background-size: cover; background-position: center center; transition-property: background-position;');

       const sp = () => {
           const x = paraId.getBoundingClientRect().top / modifier;
           const y = Math.round(x * 100) / 100;
           paraId.style.backgroundPosition = `center ${  y  }px`;
       };
       sp();
       window.addEventListener("scroll", (e) => {
           sp();
       });
   };

   parallax("#parallax-1", 8);
};

我真的只是想找到一种清除控制台错误的方法。

在此先感谢您提供任何帮助或提示。

1 个答案:

答案 0 :(得分:0)

尝试使用:paraId && paraId.setAttribute ...

window.onload = function() {

   const parallax = (id, modifier) => {
   const paraId = document.querySelector(id);

       paraId && paraId.setAttribute('style', 'background-repeat: no-repeat; background-attachment: fixed; background-size: cover; background-position: center center; transition-property: background-position;');

       const sp = () => {
           const x = paraId.getBoundingClientRect().top / modifier;
           const y = Math.round(x * 100) / 100;
           paraId.style.backgroundPosition = `center ${  y  }px`;
       };
       sp();
       window.addEventListener("scroll", (e) => {
           sp();
       });
   };

   parallax("#parallax-1", 8);
};