好吧,所以我尝试使用一种addEventListener
方法来单击event
,这将切换一个类以使我的菜单栏动画化并显示一个侧面菜单。这是我的代码
//reference to the ".menu" class
const menu = document.querySelector('.menu');
console.log(menu)
const menuButton = document.querySelector('.menu-button')
// Using your menuButton reference, add a click handler that calls toggleMenu
console.log(menuButton);
menuButton.addEventListener("click", function() {
menuButton.classList.toggle('.menu--open');
console.log('toggled');
});
<div class="header">
<img class="menu-button" src="./assets/menu.png" />
<h1>Lambda School Newsfeed</h1>
</div>
<div class="menu">
<ul>
<li>Students</li>
<li>Faculty</li>
<li>What's New</li>
<li>Tech Trends</li>
<li>Music</li>
<li>Log Out</li>
</ul>
</div>
我得到了一个返回的节点列表,并且不允许我使用事件方法,但是我似乎无法解决问题
答案 0 :(得分:0)
在此代码段.
中从.menu--open
中删除menuButton.classList.toggle('.menu--open');
//reference to the ".menu" class
const menu = document.querySelector('.menu');
console.log(menu)
const menuButton = document.querySelector('.menu-button')
// Using your menuButton reference, add a click handler that calls toggleMenu
console.log(menuButton);
menuButton.addEventListener("click", function() {
menuButton.classList.toggle('menu--open');
});
.menu--open {
border: 1px solid red;
}
.header {
cursor: pointer;
}
<div class="header">
<img class="menu-button" src="./assets/menu.png" />
<h1>Lambda School Newsfeed</h1>
</div>
<div class="menu">
<ul>
<li>Students</li>
<li>Faculty</li>
<li>What's New</li>
<li>Tech Trends</li>
<li>Music</li>
<li>Log Out</li>
</ul>
</div>
答案 1 :(得分:0)
您的代码中有两个问题:
menu--open
而不是.menu--open
menu.classList.toggle
而不是menuButton.classList.toggle
//reference to the ".menu" class
const menu = document.querySelector('.menu');
console.log(menu)
const menuButton = document.querySelector('.menu-button')
// Using your menuButton reference, add a click handler that calls toggleMenu
console.log(menuButton);
menuButton.addEventListener("click", function() {
menu.classList.toggle('menu-open');
});
.menu.menu-open {
display: none;
}
<div class="header">
<img class="menu-button" src="./assets/menu.png" />
<h1>Lambda School Newsfeed</h1>
</div>
<div class="menu">
<ul>
<li>Students</li>
<li>Faculty</li>
<li>What's New</li>
<li>Tech Trends</li>
<li>Music</li>
<li>Log Out</li>
</ul>
</div>