新手jQuery祖先导航问题

3
抱歉问题比较基础,我正在尝试为导航列表添加悬停状态,但似乎无法解决在不影响父元素 <li> 的情况下对子元素设置悬停状态。实际上,父元素 <li> 也被悬停了。我知道使用 .add/removeClass() 更理想,但对于我的测试来说,使用 .attr() 更容易。
到目前为止,我已经得到了以下代码:
我在 jsfiddle 上设置了一个演示:http://jsfiddle.net/gSPkj/,以下是代码:
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;");
});

1
请查看此帖子 - http://stackoverflow.com/questions/1327711/jquery-hover-event-with-nested-elements - Jay Blanchard
2个回答

1

更容易的方法是先定位锚点,然后找到最近的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')
    });
});

小提琴


0

你可以仅使用CSS来实现这个功能

a:hover {
    background: #123de1;
    color: #eb9028;
}

修改 JSFiddle

如果你真的需要Javascript,你可以使用event.stopPropagation()

防止事件冒泡到DOM树上,阻止任何父处理程序被通知事件。

$("#sidebarNav li.child").hover(function(e){
    e.stopPropagation();
    $(this).attr('style','background:#123de1;color:#eb9028;');
},function(e){
    e.stopPropagation();
    $(this).attr('style','background:#000;color:#fff;');
});

虽然在从子级到父级或反向移动时仍存在问题。

修改后的JSFiddle


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接