【发布时间】:2018-09-30 21:50:39
【问题描述】:
我正在尝试实现一个hover() 功能,当一个<a> 标签悬停时,它还将设置该<tr> 标签内的所有其他<a> 标签的样式。当表格中的<a> 标记之一悬停时,我想使其彼此同步,它们都将与给定表格行中的样式同步。
这是 jsfiddle:https://jsfiddle.net/o2gxgz9r/73483/
使用closest() 和parent() 方法尝试了此代码,但它不起作用:
JS:
$('#table-dropdown a').hover(function(){
//$(this).parent().siblings('a').css('text-decoration', 'underline');
$(this).closest('tr').siblings('a:not(.link)').css('text-decoration', 'underline');
//$(this).parent().siblings('a').css('color', 'red !important');
$(this).closest('tr').siblings('a:not(.link)').css('color', 'red !important');
});
HTML:
<table id="table-dropdown" style="border-collapse:collapse; border-color:initial; border-image:initial; border-width:1px; width:657px">
<tbody>
<tr>
<td style="vertical-align:top; width:64px">
<p><strong>Abbr</strong></p>
</td>
<td style="vertical-align:top; width:585px">
<p><strong>Title</strong></p>
</td>
</tr>
<tr>
<td style="vertical-align:top; width:64px">
<a class="AAA" href="#">AAA</a>
</td>
<td style="vertical-align:top; width:585px">
<a class="AAA" href="#">Heading 1</a>
<a class="link AAA" href="#"><span class="arrow"></span></a>
<p id="AAA" style="display: none;">DESCRIPTION - Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
</td>
</tr>
<tr>
<td style="vertical-align:top; width:64px">
<a href="#">BBB</a>
</td>
<td style="vertical-align:top; width:585px">
<a href="#">Heading 2</a>
<p id="BBB" style="display: none;">DESCRIPTION - Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
</td>
</tr>
<tr>
<td style="vertical-align:top; width:64px">
<a href="#">CCC</a>
</td>
<td style="vertical-align:top; width:585px">
<a href="#">Heading 3</a>
<p id="CCC" style="display: none;">DESCRIPTION - Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
</td>
</tr>
</tbody>
</table>
【问题讨论】:
-
<tr>元素没有任何<a>标签的兄弟姐妹,因此您的事件处理程序什么也不做。我想你的意思是siblings是find(这将找到所有<a>的后代标签)。 -
为什么限制自己使用文档事件(悬停)而不是纯 CSS?在这种情况下,javascript 只会增加问题,因为您的代码取决于文档选择器 (css),具体取决于 DOM 元素。使用 CSS,至少,如果你的 javascript 破坏了你的页面仍然会被样式化。
-
@ErikPhilips 因为 css 选择器没有以前的同级选择器,在这种情况下,一些
<a>标签不是同级标签,而是在单独的<td>标签中,因此,一个会悬停但其他人不会。我还想避免使用特定的类名,因为我需要一些动态的东西才能工作。 -
@RobinZigmond 谢谢。我不知道为什么我没有想到这一点。轻微问题。当我将鼠标悬停在外面时,风格就被它所困扰。我也想在悬停时删除这些样式。
-
@TheAmazingKnight 那是因为 jQuery 的
hover实际上需要 两个 函数回调。第一个在鼠标进入相关元素时执行,第二个在鼠标离开时执行。所以你只需要第二个回调来撤销第一个的效果。
标签: javascript jquery html jquery-selectors jquery-hover