我对此有点陌生。我制作了一个导航栏,其中包含一个按钮,单击该按钮可切换“活动”类。我想做到这一点,以便当导航栏打开并单击时,它会删除“活动”类。虽然我使用了 eventListener (我对此一无所知,所以我用 Google 搜索)
function toggle() {
var navButton = document.querySelector('.nav-btn-container');
navButton.classList.toggle('active')
}
var navBar = document.querySelector('#nav-bar');
navBar.addEventListener('click', function(event){
var isClickInside = navBar.contains(event.target);
if (isClickInside &&
document.querySelector('.nav-btn-container').classList.contains('active')){
document.querySelector('.nav-btn-container').classList.remove('active');
}
});
在 VS Code 中我没有收到任何错误,但在 Chrome 调试器中我收到以下错误:
Uncaught TypeError: Cannot read property 'addEventListener' of null
在事件函数中,我使用 document.querySelector('.nav-btn-container') 而不是 navBar,因为如果我将 navBar 声明移到toggle() 类之外(在第一行),当我单击按钮:
Uncaught ReferenceError: navButton is not defined
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>FCC: Product Landing Page</title>
</head>
<body>
<header id="header">
<img src="logo.png" alt="Logo" id="header-img">
<button class="nav-btn-container" onclick="toggle()">
<span class="nav-btn"></span>
</button>
<nav id="nav-bar">
<ul class="nav-list">
<li class="nav-item"><a href="#features" class="nav-
link">Features</a></li>
<li class="nav-item"><a href="#video" class="nav-
link">Unboxing</a></li>
<li class="nav-item"><a href="#purchase" class="nav-
link">Purchase</a></li>
<li class="nav-item"><a href="#reviews" class="nav-
link">Reviews</a></li>
</ul>
</nav>
CSS: https: //pastebin.com/Zd7DFCca
慕勒3428872
相关分类