悬停时高效的JS事件监听器 [英] Efficient JS Event Listener on Hover
问题描述
我编写了以下脚本,它可以正常工作.
I have written the following script, and it is perfectly working.
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);
我认为,这种方法效率很低,因为我必须实现其中一些事件侦听器.因此,我试图通过将其放在一起或使用 ClassList Toggle
函数来使其更短.不幸的是,它还没有起作用.
I think, this method is very inefficient, since I have to implement a few of these event listeners. Therefore, I have tried to make this shorter by putting it together or using the ClassList Toggle
function. Unfortunately, it has not worked yet.
如何以一种好的方式编写这段代码?
How do I write this piece of code in a good way?
[[我不使用jquery.]]
[[I am not using jquery.]]
推荐答案
很明显,这是一个Java脚本问题,这是创建可重用函数的一种方法.
As it has become clear this is a Javascript question, here is a way you can create reusable functions.
function hover(element, enter, leave){
element.addEventListener('mouseenter', enter)
element.addEventListener('mouseleave', leave)
}
然后您可以像这样传递您的元素和回调函数.
You can then pass your element and callback functions like so.
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")
})
您也可以通过修改悬停功能来减少代码行.
You can reduce the lines of code too by modifying the hover function.
function hover(element, className){
element.addEventListener('mouseenter', e => element.classList.add(className))
element.addEventListener('mouseleave', e => element.classList.remove(className))
}
然后像这样使用它.
hover(document.querySelector('h1'), "logo__container--hover")
您现在可以大规模地将其重复用于多个元素.
You can reuse this now for multiple elements scalably.
这是我以前的回答:正如JHeth所述,请使用 CSS伪类代替.
This was my previous answer: As JHeth mentioned, use CSS pseudo-classes instead.
h1{
/* Style when not hovering */
}
h1:hover{
/* Style when cursor is on element */
}
这篇关于悬停时高效的JS事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!