我正在通过JS将一些动画应用于导航栏,但在事件监听部分中我可能会重复很多次。
但是我找不到改善它的方法。
有没有一种方法可以使用循环或其他方法来监听所有这些事件,而无需为每个事件编写代码块?
let headerHome = document.querySelector('.headerHome');
let headerPlayground = document.querySelector('.headerPlayground');
let headerAbout = document.querySelector('.headerAbout');
headerHome.addEventListener('mouseover', () => {
headerHome.classList.add('mouseOverHeader');
})
headerHome.addEventListener('mouseout', () => {
headerHome.classList.remove('mouseOverHeader');
})
headerPlayground.addEventListener('mouseover', () => {
headerPlayground.classList.add('mouseOverHeader');
})
headerPlayground.addEventListener('mouseout', () => {
headerPlayground.classList.remove('mouseOverHeader');
})
headerAbout.addEventListener('mouseover', () => {
headerAbout.classList.add('mouseOverHeader');
})
headerAbout.addEventListener('mouseout', () => {
headerAbout.classList.remove('mouseOverHeader');
})
.header-menu{
display: flex;
justify-content: flex-start;
list-style-type: none;
flex-direction: column;
margin: 1em 0 0 2em;
}
.header-menu div{
margin-right: 2em;
transition: transform 1s;
transition: padding-right 1s;
transform-origin: left;
}
.header-menu a{
text-decoration: none;
color: inherit;
display: inline-block;
}
.mouseOverHeader{
transform: scale(1.1);
padding-right: 4em;
}
<nav class="header-menu">
<div class="headerHome"><a href="/index.html">Home</a></div>
<div class="headerPlayground"><a href="/playground.html">Playground</a></div>
<div class="headerAbout"><a href="/about.html">About</a></div>
</nav>
您可以为此编写一个类:
class MouseOverHeader {
constructor(selector) {
this.node = document.querySelector(selector);
if (!(this.node instanceof HTMLElement)) {
console.error('failed to find element');
return;
}
this.addEventListeners();
}
addEventListeners() {
this.node.addEventListener('mouseover', () => this.onMouseOver());
this.node.addEventListener('mouseout', () => this.onMouseOut());
}
onMouseOver() {
this.node.classList.add('mouseOverHeader');
}
onMouseOut() {
this.node.classList.remove('mouseOverHeader');
}
}
new MouseOverHeader('.headerHome');
new MouseOverHeader('.headerPlayground');
new MouseOverHeader('.headerAbout');
执行您正在寻找的方法的一种方法是将一个类添加到要使其悬停并使用querySelectorAll
的所有内容中。这是html的外观:
<nav class="header-menu">
<div class="hoverable headerHome"><a href="/index.html">Home</a></div>
<div class="hoverable headerPlayground"><a href="/playground.html">Playground</a></div>
<div class="hoverable headerAbout"><a href="/about.html">About</a></div>
</nav>
您的JavaScript将如下所示:
let hoverable = document.querySelectorAll('.hoverable');
hoverable.forEach((hoverableElement) => {
hoverableElement.addEventListener('mouseover', (event) => {
hoverableElement.classList.add('mouseOverHeader');
});
hoverableElement.addEventListener('mouseout', (event) => {
hoverableElement.classList.remove('mouseOverHeader');
});
});
保持CSS不变。