我有一个onmouseover表格上的单元格。在以下示例中,我打印出<td>
元素的内容。如果我将焦点设置在<input>
元素中,而不是按下并按住鼠标左键并移过另一个单元格,则currentTarget保持不变。
这在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>
答案 0 :(得分:3)
这种情况正在发生,因为在Edge中关注<input>
元素并从那里开始拖动时,事件的目标始终是<input>
元素。你可以这样检查一下。
function tdMouseover(e) {
console.log(e.target); // always the input in Edge
}
由于<input>
元素没有附加mouseover
事件处理程序,因此事件将传递给<input>
元素的父元素,即第一个<td>
元素。因此,即使您将鼠标悬停在其他<input>
元素上,也会将<td>
元素容器<td>
元素作为 eventTarget 触发mouseover事件,这绝对是荒谬的
如果您提供了有关您要实现的目标的更多详细信息,我们可以找到任何解决方法,但在这种情况下,Edge的行为与IE总是不同;)
更新:当Edge失败时,JavaScript验证并查找真实事件目标:
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>