我正在尝试使用单个函数来使用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)
,例如:
.toggle(className)
heroBtn.addEventListener('mouseenter', animateHomeBtn)
heroBtn.addEventListener('mouseleave', animateHomeBtn)
const animateHomeBtn = () => {
arrowEl.classList.toggle('arrow-hover')
btnTextEl.classList.toggle('btn-text-hover')
}
方法用于在使用JavaScript从元素中添加和删除类名之间切换。