如何切换“ element.classList.add”中的“ add”以使用javascript删除

问题描述 投票:0回答:1

我正在尝试使用单个函数来使用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))
})
javascript css function addeventlistener event-listener
1个回答
1
投票

解决此问题:

  1. animateHomeBtn函数中的传递字符串,如:

    heroBtn.addEventListener('mouseenter', () => animateHomeBtn('add'))
    heroBtn.addEventListener('mouseleave', () => animateHomeBtn('remove'))
    
  2. 然后更新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从元素中添加和删除类名之间切换。
© www.soinside.com 2019 - 2024. All rights reserved.