CSS / JQueryhover仅影响hover元素而非父节点
我有一个嵌套项目列表,每个项目都有自己的编辑链接。
我只希望当一个鼠标hover在list元素上时显示编辑链接。 目前,当我将鼠标hover在子元素上时,父元素也会受到影响。
$('li').hover( function(){ $(this).find('.editLink').show(); }, function(){ $(this).find('.editLink').hide(); } );
我有以下CSS来使编辑链接最初隐藏
.editLink{ display:none; }
如何制作它以便只有hover的元素显示编辑链接而不显示其他元素? 看起来像hide部分很好,但show部分会影响所有嵌套的父级。 以下是实际操作中的示例: http : //jsfiddle.net/D7yWm/
试一试。 它使用直接子选择器( http://jsfiddle.net/D7yWm/4/ ):
$(document).ready(function(){ $('li').hover( function(ev){ var li = $(this); li.parents('li').find('>.editLink').hide(); if ( ! li.find('li > .editLink:visible').length ) { li.find('>.editLink').show(); } }, function(){ var li = $(this); li.find('>.editLink').hide(); li.parents('li:first').find('>.editLink').show(); } ); });
如果您希望将其本地化为文本,则必须将文本包装在或其他内容中,然后使用它。
ul { list-style-position: inside; }
如果这对您不起作用,您可能需要考虑添加子弹的不同方式。 或者用它作为计算rest时间的起点……
您需要在处理程序中停止传播事件
$(document).ready(function(){ $('li').hover( function(e){ e.stopPropagation(); $(this).find('.editLink').show(); }, function(){ $(this).find('.editLink').hide(); } ); });
如果您希望将父级的.editlink
从他们移动到他们的孩子后隐藏,那么您可以使用:
$('li').hover( function(e){ e.stopPropagation(); $(this).parents('li').trigger('mouseleave'); $(this).children('.editLink').show(); }, function(e){ e.stopPropagation(); $(this).parents('li').trigger('mouseleave'); $(this).children('.editLink').hide(); } );
DEMO
这与您的问题不完全相同,但它可能会帮助其他人。 我的想法是突出顶部徘徊的孩子而不影响下面的父母: http : //jsfiddle.net/skibulk/mcq6Lvw3/6/
$("div").hover( function (e) { e.stopPropagation(); $(this).addClass('active').parents().removeClass('active'); }, function (e) { $(this).removeClass('active').parent().addClass('active'); } );
由于
是嵌套在彼此之内,当你将鼠标hover在孩子身上时,父母仍在“盘旋”。 要阻止显示所有父链接,您可以遍历所有父
并隐藏父项的链接。 另外,使用.children()
仅选择直接子项,而不是嵌套子项。
$(document).ready(function(){ $('li').hover( function(){ $(this).parents('li').each(function(){$(this).children('.editLink').hide();}); $(this).children('.editLink').show(); }, function(){ $(this).find('.editLink').hide(); } ); });
这是一个工作的jsfiddle 。