如何仅将当前li悬停在嵌套ul中? [英] How to hover only the current li in nested ul?
问题描述
我有一个嵌套列表:
li:hover {
background-color: lightgray;
}
ul li ul li:hover {
font-weight: bold;
}
<ul>
<li>fnord
<ul>
<li>baz</li>
<li>foo
<ul>
<li>baz</li>
<li>foo</li>
</ul>
</li>
</ul>
</li>
<li>gnarf
<ul>
<li>baz</li>
<li>foo
<ul>
<li>baz</li>
<li>yolo</li>
</ul>
</li>
</ul>
</li>
</ul>
问题是,悬停"foo"也将悬停"fnord"及其所有li
元素.如何仅将鼠标实际上悬停在li
上?
Problem is, hovering "foo" will also hover "fnord" and all of its li
elements. How do I hover only the li
my mouse is actually hovering over?
嵌套是可变的,从理论上讲可以是无止境的.
The nesting is variable and can, in theory, be endless.
我已经设置了 JSFiddle .
推荐答案
我相信,仅使用CSS就能获得的最接近的效果是从悬停元素的子元素中删除悬停样式...这对父母没有帮助.
I believe the closest you can get with just CSS is to remove the hover styling from the children of the hovered elements... which doesn't help the parents.
li:hover {
background-color: lightgray;
}
li:hover {
font-weight: bold;
}
li:hover ul {
background-color: white;
font-weight: normal;
}
<ul>
<li>fnord
<ul>
<li>baz</li>
<li>foo
<ul>
<li>baz</li>
<li>foo</li>
</ul>
</li>
</ul>
</li>
<li>gnarf
<ul>
<li>baz</li>
<li>foo
<ul>
<li>baz</li>
<li>foo</li>
</ul>
</li>
</ul>
</li>
</ul>
对于您发现的重复项,可接受的答案是我看到的使用e.stopPropagation
使用JavaScript做到这一点的最佳方法:
The accepted answer on the duplicate you found is the best way I've seen to do this with JavaScript, using e.stopPropagation
: Cascading <li>-hover effect using CSS. You'll want to be more specific than 'all lis' in that selector though:
$('li').mouseover(function(e)
{
e.stopPropagation();
$(this).addClass('currentHover');
});
$('li').mouseout(function()
{
$(this).removeClass('currentHover');
});
.currentHover {
background-color: red;
}
li.currentHover ul {
background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="container">
<li>fnord
<ul>
<li>baz</li>
<li>foo
<ul>
<li>baz</li>
<li>foo</li>
</ul>
</li>
</ul>
</li>
<li>gnarf
<ul>
<li>baz</li>
<li>foo
<ul>
<li>baz</li>
<li>foo</li>
</ul>
</li>
</ul>
</li>
</ul>
JSFiddle .
这篇关于如何仅将当前li悬停在嵌套ul中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!