所以我写了一个函数,highlight每当我点击一个特定的菜单项时添加一个类,highlight如果我点击另一个菜单项则删除该类
我的问题是,当我将屏幕缩小到移动视图时,该类highlight仍然适用,我不知道如何防止它出现?
我使用了 window.innerWidth 但当我缩小屏幕时它似乎不起作用
const menu = document.querySelector('#mobile-menu');
const menuLinks = document.querySelector('.navbar__menu');
const activeMenu = e => {
const elem = document.querySelector('.highlight');
// adds 'highlight' class to my menu item here
if (window.innerWidth > 768) {
e.target.className = 'navbar__links highlight';
}
// it doesn't remove the class 'highlight' when I shrink my screen
// this only removes the 'highlight' class if I click on a different menu item
if (elem || window.innerWidth < 768) {
elem.classList.remove('highlight');
}
};
menuLinks.addEventListener('click', activeMenu);
// Tried to add resize event, but this didn't work, so not sure how
to write it
const removeActiveMenu = () => {
const elem = document.querySelector('.highlight');
if (window.innerWidth < 768) {
elem.classList.remove('highlight');
}
};
menuLinks.addEventListener('resize', removeActiveMenu);
有谁知道如何防止我的highlight班级出现在 768 像素以下的屏幕尺寸上?
我试图在下面添加一个调整大小事件,但没有成功,所以不确定我应该如何实现它?
这是 HTML
// Realized my Logo isn't highlighting the home nav when I click it
<a href="#home" id="navbar__logo">COLOR</a>
<div class="navbar__toggle" id="mobile-menu">
<span class="bar"></span> <span class="bar"></span>
<span class="bar"></span>
</div>
<ul class="navbar__menu">
<li class="navbar__item">
<a href="#home" class="navbar__links" id="homePage">Home</a>
</li>
<li class="navbar__item">
<a href="#about" class="navbar__links" id="about-us">About
Us</a>
</li>
<li class="navbar__item">
<a href="#services" class="navbar__links"
id="service">Services</a>
收到一只叮咚
米脂
相关分类