如何仅突出显示嵌套表的最里面的表行? [英] How do I highlight only the innermost table row of a nested table?
问题描述
我有几个嵌套表,我想突出显示鼠标指针下方的最里面的行.我该怎么办?
I have several nested tables and I want to highlight the innermost row that is below the mouse pointer. How can I do that?
一些指针:我使用嵌套表来显示递归表格数据.这些表可以嵌套10层深度.嵌套就像您期望的那样:
Some pointers: I use nested tables to display recursive tabular data. The tables can be nested 10 levels deep. The nesting is just like you would expect:
<table><tr><td>
<table><tr><td>
<table><tr><td>
...
可能存在没有嵌套表的行.我想要在鼠标光标下方的最深/最内层<tr>
上突出显示.
There are can be rows which don't have nested tables. I want the highlight on the deepest / innermost <tr>
that is under the mouse cursor.
我可以使用CSS或jQuery.
I can use CSS or jQuery.
推荐答案
我想提出一些更优雅(至少更短)的东西:
I would like to propose something slightly more elegant (at least shorter):
$('#mainTable').on('mouseenter mouseleave', 'tr', {el: false}, function (e) {
var hl = e.data.el;
hl && hl.removeClass('hover');
e.data.el = (e.type === 'mouseenter') ?
$(this).addClass('hover') :
$(this).parent().closest('tr:hover').addClass('hover');
});
它将当前突出显示的节点存储在(持久)委托数据对象中,并处理鼠标事件,如下所示:
It stores the currently highlighted node in the (persistent) delegated data object and handles the mouse events, as follows:
- 如果鼠标进入元素(最里面的鼠标悬停的
tr
),请删除当前突出显示并突出显示当前元素. - 如果鼠标离开元素,则突出显示最接近的
hovered
祖先tr
而不是当前的祖先.
- If the mouse enters an element (the innermost hovered
tr
), remove the current highlight and highlight current element. - If the mouse leaves an element, highlight the closest
hovered
ancestortr
instead of the current one.
使用事件委派(例如,带有选择器的$.delegate()
和$.on()
)的解决方案的主要优点是仅附加一个单个事件侦听器(相比之下,使用传统方法可能会产生数十个,数百个或更多事件) ,按元素,方法),并能够支持对元素的动态更改.
The main advantages of solutions using event delegation (such as $.delegate()
and $.on()
with a selector) are attaching only a single event listener (compared to potentially dozens, hundreds or more using traditional, per-element, methods) and being able to support dynamic changes to the element.
我选择了mouseover
事件而不是使用该解决方案,因为我相信enter/leave事件应该提供更好的性能,因为它们不会冒泡.
I chose this solution over the use if the mouseover
event since I believe the enter/leave events should provide better performance, as they do not bubble.
注意:
它在jQuery 1.9.x中有问题,但据我测试,其余版本均可使用,包括较新和较旧的版本.这是由于该版本的:hover
伪选择器存在问题.
It has a problem with jQuery 1.9.x but works with the rest, as far as I tested, including newer and older releases. This is due to an issue with the :hover
pseudo-selector in that version.
CSS 4级具有建议的功能,该功能可以使用CSS启用此功能仅:
CSS level-4 has a suggested feature that can enable this behavior using CSS only:
tr, !tr:hover tr:hover {
background-color: transparent;
}
tr:hover {
background-color: #DDFF75;
}
当然,由于此功能不是当前的最终功能,并且目前尚不受任何主流浏览器的支持,因此本节将作为将来的参考.
Of course, since this feature is not currently final and is not supported by any major browser at the moment, this section will serve as future reference.
这篇关于如何仅突出显示嵌套表的最里面的表行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!