【问题标题】:Mouseover event over multiple elements flickers多个元素上的鼠标悬停事件闪烁
【发布时间】:2020-04-01 03:16:38
【问题描述】:

我受困于创建精简的代码,目前只想使用 JavaScript。

http://jsfiddle.net/TheOne_TheMany/30zdkrys

我遇到的问题是鼠标悬停状态,当它越过 <li> 时它可以工作,但在越过 <div> 删除区域时会闪烁。我知道为什么会这样(经过大量研究)。所以我尝试了mouseleave,但我需要在<li> 上有多个ID 才能使其工作。

是否有一种更简洁的编码方式,无需创建这么多 ID 或多个事件侦听器。特别是如果我要添加更多<li> 或删除它们。

提前感谢您的帮助。

【问题讨论】:

  • 我认为这是因为你有相互竞争的鼠标悬停 div,当它动画时,中间有一个汗水点,他们来回抛出事件。您可能需要提供 z-index。

标签: javascript html-lists addeventlistener mouseover


【解决方案1】:

问题是当您将子 <div> 悬停在 <li> 前面时,因此目标不是 <li>,而是 <div>。我强烈建议你在 CSS 中使用 hover 而不是 JavaScript 来解决它,但既然你想要这样,那就去吧:

mouseOver 函数中,添加另一个if 语句来检查鼠标是否在删除按钮内。然后,将类添加到<li> 和按钮。

const mouseOver = function(item){

    // Btn animation'
    if (item.target === btnSend) {
        item.target.classList.add('btnOver');
    }

    // Li animation
    if (item.target.matches('li')) {
        item.target.classList.add('onLi');
        item.target.lastChild.classList.add('containerDelete');
    }

    if (item.target.matches('.deleteMe')) {
       item.target.parentNode.parentNode.classList.add('onLi');
       item.target.classList.add('containerDelete');
    }

    item.stopPropagation;

}

然后,在 mouseLeave 函数上,添加另一个 if 语句来检查鼠标是否从 <li> 和删除按钮离开。
在其中,您还可以检查目标是<li> 还是按钮<div>,因为您必须以不同的方式删除类。

const mouseLeave = function(item){

    // Btn animation   
    if(item.target === btnSend){
        item.target.classList.remove('btnOver');
    } else if (!item.toElement.matches('li') && !item.toElement.matches('.deleteMe')) {
      if (item.target.tagName === 'LI') {
        item.target.classList.remove('onLi');
        item.target.lastChild.classList.remove('containerDelete');
      }
      if (item.target.tagName === 'DIV') {
        item.target.parentNode.parentNode.classList.remove('onLi');
        item.target.parentNode.classList.remove('containerDelete');
        console.log('ok')
      }
    }

}

【讨论】:

  • 太棒了。非常感谢,真的很感激。
猜你喜欢
  • 1970-01-01
  • 2014-10-21
  • 2013-03-03
  • 1970-01-01
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
  • 2019-06-26
  • 2020-04-21
相关资源
最近更新 更多