2 回答
TA贡献1821条经验 获得超4个赞
您可以使用querySelectorAllalong withforEach来获取所有内容.navbar__links并在您将其放入视图highlight中时从它们中删除类。resizewindowmobile
您的代码也在生成控制台errors,因为您试图remove从element单击菜单项时不存在的类进行分类,并且window < 768
//Remove class from others when click on li
if (elem && window.innerWidth < 768 || elem) {
elem.classList.remove('highlight');
}
在调整大小功能上使用此代码:
//on resize
window.addEventListener('resize', function(event) {
const links = document.querySelectorAll('.navbar__links');
links.forEach(function(x) {
if (window.innerWidth < 768) {
x.classList.remove('highlight'); //remove highlught class
}
})
});
我已经修复了你的问题code并且正在按预期工作。
现场演示:
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.classList.add('highlight');
}
//Remove class from others when click on li
if (elem && window.innerWidth < 768 || elem) {
elem.classList.remove('highlight');
}
};
//Click event on li
menuLinks.addEventListener('click', activeMenu);
//on resize
window.addEventListener('resize', function(event) {
const links = document.querySelectorAll('.navbar__links');
links.forEach(function(x) {
if (window.innerWidth < 768) {
x.classList.remove('highlight'); //remove highlught class
}
})
});
.highlight {
background: red;
}
<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>
</li>
<li class="navbar__btn">
<a href="#sign-up" class="button navbar__links" id="signup">Sign Up</a>
</li>
</ul>
TA贡献1836条经验 获得超3个赞
解决方案:
function activeMenu(e) {
let links = document.querySelectorAll('.navbar__links');
if (window.innerWidth > 768) {
links.forEach(link => {
link.classList.remove("highlight");
})
e.classList.add("highlight");
} else {
e.classList.remove("highlight");
}
}
.highlight {color:red !important}
<div id="mobile-menu">#mobile-menu</div>
<div class="navbar__menu">
<div onclick="activeMenu(this)" class="navbar__links">navbar__links</div>
<div onclick="activeMenu(this)" class="navbar__links">navbar__links</div>
<div onclick="activeMenu(this)" class="navbar__links">navbar__links</div>
</div>
添加回答
举报