Javascript 在鼠标悬停在 Microsoft Edge / IE 中的奇怪行为上



我有一个鼠标悬停在桌子上的单元格上。在下面的示例中,我打印出 <td> 元素的内容。如果我在<input>元素中设置焦点,然后按住鼠标左键并越过另一个单元格,则当前目标保持不变。

这发生在 Microsoft Edge 中,在 Chrome 中,我得到了鼠标所在的单元格的打印输出,正如预期的那样。

 $('#tableProperties').on('mouseover','.mycell', tdMouseover);
 
 function tdMouseover(e) {
    var mycell = e.currentTarget;
    console.log("myCell: "+mycell.textContent);
    }
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <table width="500px" id="tableProperties">
          <tr><td class="mycell"><input value="Cell 1"></input></td></tr>
          <tr><td class="mycell">Cell 2</td></tr>
          <tr><td class="mycell">Cell 3</td></tr>
          <tr><td class="mycell">Cell 4</td></tr>
          <tr><td class="mycell">Cell 5</td></tr>
          <tr><td class="mycell">Cell 6</td></tr>
</table>

之所以发生这种情况,是因为在 Edge 中,当您聚焦<input>元素并开始从那里拖动时,事件的目标始终是<input>元素。你可以像这样检查。

function tdMouseover(e) {
    console.log(e.target); // always the input in Edge 
}

由于 <input> 元素没有附加mouseover事件处理程序,因此事件将传递给<input>元素的父元素,即第一个<td>元素。因此,mouseover 事件是使用 <input> 元素容器<td>元素作为 eventTarget 触发的,即使您将鼠标悬停在其他 <td> 元素上也是如此,这绝对是可笑的。

如果您提供有关要实现的目标的更多详细信息,我们可以找到任何解决方法,但在这种情况下,Edge 的行为与 IE 一直不同;)

更新:JavaScript 验证并在 Edge 失败时查找真实事件目标:

var $currentHoverElement=null;
$('#tableProperties').on('mouseover','.mycell', tdMouseover);
function tdMouseover(e) {
  var $hoverElement = $(e.currentTarget), hoffset=$hoverElement.offset();
  /* Check if this is the real over Element */
  if(e.clientY<hoffset.top||e.clientY>hoffset.top+$hoverElement.outerHeight()){
    console.log("Finding out real hover element");
    var $actual=$('.mycell').filter(function(i,el){
      var $el=$(el),eoffset=$el.offset();
      return e.clientY>eoffset.top&&e.clientY<eoffset.top+$el.height();
    });
    if($actual.length)$hoverElement=$actual.eq(0);
  }
  if($currentHoverElement)$currentHoverElement.removeClass('hovered');
  $hoverElement.addClass('hovered');
  $currentHoverElement=$hoverElement;
}
.hovered{
  color: red;
}
.hovered input{
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table width="500px" id="tableProperties">
  <tr>
    <td class="mycell">Cell 1</td>
  </tr>
  <tr>
    <td class="mycell"><input value="Cell 2"></td>
  </tr>
  <tr>
    <td class="mycell">Cell 3</td>
  </tr>
  <tr>
    <td class="mycell">Cell 4</td>
  </tr>
  <tr>
    <td class="mycell">Cell 5</td>
  </tr>
  <tr>
    <td class="mycell">Cell 6</td>
  </tr>
</table>

最新更新