【问题标题】:Nested span mouseover issue in IEIE中的嵌套跨度鼠标悬停问题
【发布时间】:2016-08-18 14:44:21
【问题描述】:

我有嵌套的 span 元素,并且有父 span 的 mouseovermouseout 事件

<span id='parent' onmouseover='showChild()' onmouseout='hideChild()'>
    <span id='child'></span>
</span>

我在parent span 上显示child span 上的mouseover 并将其隐藏在mouseout 上来自parent

这一切在 Firefox 和 chrome 中都可以正常工作,但在 IE 中,只要鼠标经过子元素,IE 就会将其视为鼠标离开父元素并隐藏子元素。

对于 IE 是否有任何解决方法或正确的方法?

我可以将相同的事件放在子跨度中,这也应该在 IE 中工作,但这是否是正确的方法?

【问题讨论】:

    标签: javascript html css internet-explorer dom-events


    【解决方案1】:

    使用 css 从父 div 中移除指针事件:

    #parent * {
         pointer-events: none;
    }
    

    【讨论】:

    • 这只适用于IE11,因为他的IE有问题。
    【解决方案2】:

    您可以通过使用onmouseleave 而不是onmouseout 来解决此问题:

    <span id='parent' onmouseover='showChild()' onmouseleave='hideChild()'>
        <span id='child'></span>
    </span>
    

    当您将鼠标悬停在孩子上时,上述内容不会触发hideChild(),但在父子之间移动时会触发showChild()

    为防止这种情况,您可以将onmouseover 替换为onmouseenter

    <span id='parent' onmouseenter='showChild()' onmouseleave='hideChild()'>
        <span id='child'></span>
    </span>
    

    检查此fiddle。打开控制台进行输出。

    【讨论】:

    • 奇怪的是你的解决方案在小提琴中工作但是当我在我的代码中尝试它时它仍然无法工作:(
    • 很奇怪。您在哪个版本的 IE 上试用?
    • IE 11。但是我找到了解决方法。我发布了我的答案。谢谢! :)
    • 不错!你最后还在使用onmouseleaveonmouseout吗?
    • 不,我正在使用mouseovermouseout,只是我最初使用的。你可以看看我的回答
    【解决方案3】:

    在这种情况下,您只需要使用 Event.target 来检查事件目标是否不是孩子。

    这是一个有效的 sn-p:

    function showChild(e) {
      e = e || window.event;
      var child = document.getElementById("child");
      if (e.target !== child) {
        child.style.display = "inline-block";
      }
    }
    
    function hideChild(e) {
      e = e || window.event;
      var child = document.getElementById("child");
      if (e.target !== child) {
        child.style.display = "none";
      }
    }
    #parent {
      background-color: yellow;
      width: 300px;
      display: block;
      height:100px;
    }
    #child {
      background: blue;
      color: white;
      width:auto;
      height:auto;
    }
    <span id="parent" onmouseover="showChild(event)" onmouseout="hideChild(event)">Parent
        <span id="child">Child</span>
    </span>

    这会给你你所需要的。

    注意:

    在 Firefox 中,您应该将 event 参数传递给您的函数,例如 showChild(event),否则它将声明事件 e is undefined

    【讨论】:

      【解决方案4】:

      找到解决方法。

      我用display:inline-block 替换了div 的父跨度,现在它在任何地方都可以使用!

      谢谢!

      【讨论】:

      • Chrome onwheel 事件上的类似问题,其中轮事件需要位于 div 内的不同跨度上。 div 正在捕捉事件,而不是通过跨度。因此,我更改为答案中所述的嵌套 div,现在一切正常。 :-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      相关资源
      最近更新 更多