导出Codepen自定义首页后出现addEventListener空值错误求助
Hey there! Let's fix that error and get your animations working again. The "Cannot read property 'addEventListener' of null" error pops up because your code is trying to access elements that either don't exist, aren't loaded yet, or are being messed up by broken HTML syntax. Here's the breakdown and fixes:
What's Going Wrong
- Broken HTML Structure:
- You missed an
=in<html lang"en">(it should be<html lang="en">). - There's an unclosed
<div>inside your<head>tag, which completely throws off how the browser parses your page. This makes it impossible for your JS to find the.leftand.rightelements correctly.
- You missed an
- Missing
.containerElement: Your JS references a.containerclass, but there's no such element in your original HTML—even if you fixed the first issue, you'd hit another error when trying to modify its classes. - Script Placement: Putting the script in the
<head>means it runs before the DOM is fully loaded, even withwindow.onload. Placing it at the end of the<body>is more reliable and avoids this problem entirely.
Fixed Code
Corrected HTML (with proper structure and added container)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Custom Homepage</title> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <!-- Add the container div your JS expects --> <div class="container"> <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> <!-- Move script to end of body to ensure all elements are loaded first --> <script src="script.js"></script> </body> </html>
Simplified JavaScript (no need for window.onload now)
// All elements are loaded and ready when this runs 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"); });
Why This Works
- Your HTML is now properly structured, so the browser can parse all elements without confusion.
- The
.containerelement is now present, matching what your JavaScript references. - Placing the script at the end of the
<body>guarantees that all DOM elements are fully loaded before your JS tries to interact with them—no more "null" errors blocking your animations.
内容的提问来源于stack exchange,提问作者AnnoyingRain5
相关产品推荐
相关产品推荐

