悬停时高效的 JS 事件监听器

mic*_*ael 3 html javascript css class

我编写了以下脚本,并且它运行良好。

function LogoHoverAdd() {
    this.classList.add("logo__container--hover");
}
function LogoHoverRemove() {
    this.classList.remove("logo__container--hover");
}

var logo = document.querySelector("h1");
logo.addEventListener("mouseover", LogoHoverAdd);
logo.addEventListener("mouseout", LogoHoverRemove);
Run Code Online (Sandbox Code Playgroud)

我认为,这种方法效率非常低,因为我必须实现其中一些事件侦听器。因此,我尝试通过将其放在一起或使用该ClassList Toggle函数来缩短它。不幸的是,它还没有发挥作用。

我该如何写好这段代码呢?

[[我没有使用jquery。]]

Mik*_*ike 11

很明显这是一个 Javascript 问题,这是一种创建可重用函数的方法。

function hover(element, enter, leave){
  element.addEventListener('mouseenter', enter)
  element.addEventListener('mouseleave', leave)
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以像这样传递元素和回调函数。

hover(document.querySelector('h1'), e => {
  // On hover
  e.target.classList.add("logo__container--hover")
}, e => {
  // On exit hover
  e.target.classList.remove("logo__container--hover")
})
Run Code Online (Sandbox Code Playgroud)

您也可以通过修改悬停功能来减少代码行。

function hover(element, className){
  element.addEventListener('mouseenter', e => element.classList.add(className))
  element.addEventListener('mouseleave', e => element.classList.remove(className))
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它。

hover(document.querySelector('h1'), "logo__container--hover")
Run Code Online (Sandbox Code Playgroud)

您现在可以将其重复用于多个元素。


这是我之前的回答:正如 JHeth 提到的,使用CSS 伪类代替。

h1{
  /* Style when not hovering */
}

h1:hover{
  /* Style when cursor is on element */
}
Run Code Online (Sandbox Code Playgroud)