【问题标题】:Newbie jQuery ancestory navigation issue新手 jQuery 祖先导航问题
【发布时间】:2013-01-25 14:25:27
【问题描述】:

为基本问题道歉,但我正在尝试将悬停状态添加到导航列表中,并且似乎无法解决如何在不影响父级<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;");
});

【问题讨论】:

标签: jquery html


【解决方案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')
    });
});

FIDDLE

【讨论】:

    【解决方案2】:

    你只能用 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 2013-12-08
      • 2018-10-02
      • 2012-01-07
      相关资源
      最近更新 更多