我正在尝试使用单个函数来添加和删除使用 javascript 的类。我尝试创建一个将操作作为参数(添加或删除)来从元素中添加/删除类的函数,而不是拥有两个几乎相同的函数。
当我传入参数时,js似乎无法识别它。
这就是我目前正在处理的内容:
// function that adds or removes a class
const animateHomeBtn = (axn) => {
arrowEl.classList.axn('arrow-hover')
btnTextEl.classList.axn('btn-text-hover')
}
// event listener to add a class when mouse hovers an element
heroBtn.addEventListener('mouseenter', () => animateHomeBtn(add))
})
// event listener to remove a class when mouse move out of element
heroBtn.addEventListener('mouseenter', () => animateHomeBtn(remove))
})
最佳答案
要解决此问题:
在
animateHomeBtn
函数中传递字符串,例如:heroBtn.addEventListener('mouseenter', () => animateHomeBtn('add')) heroBtn.addEventListener('mouseleave', () => animateHomeBtn('remove'))
然后更新
animateHomeBtn
函数,例如:const animateHomeBtn = (axn) => { arrowEl.classList[axn]('arrow-hover') btnTextEl.classList[axn]('btn-text-hover') }
或者,您可以简单地使用 .toggle(className)
像:
heroBtn.addEventListener('mouseenter', animateHomeBtn)
heroBtn.addEventListener('mouseleave', animateHomeBtn)
const animateHomeBtn = () => {
arrowEl.classList.toggle('arrow-hover')
btnTextEl.classList.toggle('btn-text-hover')
}
.toggle()
方法用于使用 JavaScript 在元素中添加和删除类名之间进行切换。
关于javascript - 如何使用javascript切换 'add'中的 "element.classList.add"以删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60796520/