gpt4 book ai didi

javascript - "Cannot read property ' addEventListener ' of null"仅在从codepen导出后出现

转载 作者:行者123 更新时间:2023-12-03 02:43:59 25 4
gpt4 key购买 nike

我正在使用codepen制作自定义主页它一直有效,直到我将其导出为止...无法读取 null 属性“addEventListener”。我所有的动画都不起作用。 这是我的 JS 代码

        window.onload = function(){
const left = document.querySelector(".left");
const right = document.querySelector(".right");
const container = document.querySelector(".container");

left.addEventListener("mouseenter", () => {
container.classList.add("hover-left");
});

left.addEventListener("mouseleave", () => {
container.classList.remove("hover-left");
});

right.addEventListener("mouseenter", () => {
container.classList.add("hover-right");
});

right.addEventListener("mouseleave", () => {
container.classList.remove("hover-right");
});
}

和我的 HTML

  <!DOCTYPE html>
<html lang"en">
<head>
<meta charset="utf-8">
<title>...</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="script.js"></script>
<div>
</head>
<body>
<div class="split left">
<h1>My Email</h1>
<a href="https://mail.google.com/mail/u/0/#inbox/" class="button">Go There</a>
</div>
<div class="split right">
<h1>Google</h1>
<a href="https://www.google.com.au/" class="button">Go There</a>
</div>
</div>
</body>
</html>

我希望有人能帮我解决这个错误

最佳答案

您需要在页面加载时运行 JavaScript。在 script.js因为当前运行时元素还不存在:

window.onload = function(){
// rest of your code
}

Codepen 会自动为您完成此操作,这就是它在那里工作的原因。

<小时/>

编辑:您的开头<div>元素也在 <head> 内元素并且缺少 class="container"属性。

关于javascript - "Cannot read property ' addEventListener ' of null"仅在从codepen导出后出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48184976/

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