对基本问题表示歉意,但我正在尝试将悬停状态添加到导航列表,但似乎无法弄清楚如何在不影响父级的情况下使悬停状态悬停在子级上 <li>
.家长<li>
技术上也在徘徊。我知道 .add/removeClass()
更理想,但对于我的测试,使用 .attr()
更容易.
到目前为止我有:
我在 http://jsfiddle.net/gSPkj/ 设置了一个 jsfiddle但下面是代码-
HTML-
<div id="sidebarNav">
<ul>
<li class="parent"><a href="page1.html">Page 1</a></li>
<li class="parent"><a href="page2.html">Page 2</a></li>
<li class="parent"><a href="page3.html">Page 3</a></li>
<li class="parent"><a href="page4.html">Page 4</a>
<ul>
<li class="child"><a href="subpage_of_4-2.html">Subpage of 4 - 1</a></li>
<li class="child"><a href="subpage_of_4-2.html">Subpage of 4 - 2</a></li>
</ul>
</li>
</ul>
jQuery-
$("#sidebarNav li.parent").hover(function(){
$(this).attr("style","background:#123de1;color:#eb9028;");
},function(){
$(this).attr("style","background:#fff;color:#000;");
});
$("#sidebarNav li.child").hover(function(){
$(this).attr("style","background:#123de1;color:#eb9028;");
$(this).parents(".parent").attr("style","background:#fff;color:#000;");
},function(){
$(this).attr("style","background:#fff;color:#000;");
});
最佳答案
定位 anchor ,然后找到最近的 li 元素来附加样式会更容易。我会这样做:
$("#sidebarNav li > a").on('mouseenter mouseleave', function(e) {
$(this).closest('li').css({
background: (e.type == 'mouseenter' ? '#123de' : '#fff'),
color: (e.type == 'mouseenter' ? '#eb9028' : '#000')
});
});
关于jquery - 新手 jQuery 祖先导航问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14523756/