gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot read property 'setAttribute' of null (console error)

转载 作者:行者123 更新时间:2023-11-28 03:39:15 25 4
gpt4 key购买 nike

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

未捕获类型错误:无法读取 null 的属性“setAttribute”

这里是一个工作示例的 codepenn 链接:

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);
};

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

预先感谢您提供有关如何解决此问题的任何帮助或提示。

最佳答案

尝试使用: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);
};

关于javascript - 未捕获的类型错误 : Cannot read property 'setAttribute' of null (console error),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57437151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com