我试图只创建一个简单的响应式汉堡包按钮,但是当我将窗口调整为更小的窗口时,汉堡包按钮不会出现。
当我打开控制台时,会出现此错误消息。我到处搜索,没有什么对我有用
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
虽然它是基本的 HTML 和 CSS,但我不知道错误在哪里。
有什么错误?
const hamburger = document.querySelector(".hambuger"); const navMenu = document.querySelector(".nav-menu"); hamburger.addEventListener("click", () => { hamburger.classList.toggle("active"); navMenu.classList.toggle("active"); }); document.querySelectorAll("nav-link").forEach((n) => n.addEventListener("click", () => { hamburger.classList.remove("active"); navMenu.classList.remove("active"); }) ); * { padding: 0; margin: 0; box-sizing: border-box; } header { background-color: #262626; } li { list-style: none; } a { color: white; text-decoration: none; } .navbar { min-height: 70px; display: flex; justify-content: space-between; align-items: center; padding: 0 24px; } .nav-menu { display: flex; justify-content: space-between; align-items: center; gap: 60px; } .nav-branding { font-size: 2rem; } .nav-link { transition: 0.7s ease; } .nav-link:hover { color: dodgerblue; } .hamburger { display: none; cursor: pointer; } .bar { display: block; width: 25px; height: 3px; margin: 5px auto; -webkit-transition: all 0.3s ease-in-out; transition: all 0.3s ease-in-out; background-color: white; } @media (max-width: 768px) { .hanburger { display: block; } .hamburger.active .bar:nth-child(2) { opacity: 0; } .hamburger.active .bar:nth-child(1) { transform: translateY(8px) rotate(45deg); } .hamburger.active .bar:nth-child(3) { transform: translateY(-8px) rotate(-45deg); } .nav-menu { position: fixed; left: -100%; top: 70px; gap: 0; flex-direction: column; background-color: #262626; width: 100%; text-align: center; transition: 0.3s; } .nav-item { margin: 16px 0; } .nav-item.active { left: 0; } } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="style.css" /> <title>document</title> </head> <body> <header> <nav class="navbar"> <a href="#" class="nav-branding">DEV.</a> <ul class="nav-menu"> <li class="nav-item"> <a href="#" class="nav-link">Home</a> </li> <li class="nav-item"> <a href="#" class="nav-link">About</a> </li> <li class="nav-item"> <a href="#" class="nav-link">Contact</a> </li> </ul> <div class="hamburger"> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </div> </nav> </header> <script src="script.js"></script> </body> </html>
const hamburger = document.querySelector(".hambuger"); const navMenu = document.querySelector(".nav-menu");
在这里,您可能打错了“.hamburger”。因此,汉堡类的事件监听器返回 null。