是否可以在 Javascript 中的特定条件下停用 addeventlistener (mouseover/mouseout)?

Is it possible to deactivate addeventlistener (mouseover/mouseout) on a specific condition in Javascript?

let currentColor = 0

function makeHover () {
        console.log(currentColor);
            svgAll.forEach(item => {
                item.addEventListener('mouseover', event => {
                    event.target.style.fill = "rgb(168,168,168)";
                    event.target.style.pointerEvents = "all";
                    event.target.style.cursor = "pointer";
                    event.target.style.strokeOpacity = "1";
                    event.target.style.fillOpacity = "0.3";
                    event.target.style.transitionDuration = "0.5s";
                    event.target.style.transitionTimingFunction = "ease-in";
                })
            })

            svgAll.forEach(item => {
                item.addEventListener('mouseout', event => {
                    event.target.style.fill = "none";
                    event.target.style.stroke = "white";
                    event.target.style.pointerEvents = "all";
                    event.target.style.strokeOpacity = "1";
                    event.target.style.fillOpacity = "0.1";
                    event.target.style.transitionDuration = "0.5s";
                    event.target.style.transitionTimingFunction = "ease-out";
                })
            })
        }

在此代码中,我只想在以下情况下启用悬停效果:

if (currentColor === 0)
        {makeHover ()}

我在 SVG 上使用这个效果,控制台给出了 currentColor = 1 当满足另一个条件时设置 currentColor = 1。在 currentColor = 1 时悬停仍然有效,甚至可以停用已激活的悬停效果吗?

您只需将样式包装在 if 语句中:

svgAll.forEach(item => {
  item.addEventListener('mouseover', event => {
    if (currentColor === 0) {
      event.target.style.fill = "none";
      event.target.style.stroke = "white";
      event.target.style.pointerEvents = "all";
      event.target.style.strokeOpacity = "1";
      event.target.style.fillOpacity = "0.1";
      event.target.style.transitionDuration = "0.5s";
      event.target.style.transitionTimingFunction = "ease-out";
    }
  })
})
svgAll.forEach(item => {
  item.addEventListener('mouseout', event => {
    if (currentColor === 0) {
      event.target.style.fill = "none";
      event.target.style.stroke = "white";
      event.target.style.pointerEvents = "all";
      event.target.style.strokeOpacity = "1";
      event.target.style.fillOpacity = "0.1";
      event.target.style.transitionDuration = "0.5s";
      event.target.style.transitionTimingFunction = "ease-out";
    }
  })
})