【问题标题】:highlight menu items based on associated content基于相关内容突出显示菜单项
【发布时间】:2011-07-22 00:41:08
【问题描述】:

我正在使用 jQuery 根据菜单项选择在网站上显示内容。每个菜单项都附有一个与内容 div 容器匹配的数字。

    $(".main-cat").hover(function() {
    $(this).parent().find("div.arrow-right").remove();
    $(this).after('<div class="arrow-down"></div>');
    $(this).addClass('selected');
    $(this).css('cursor', 'pointer');
},
    function() {
    $(this).removeClass('selected');
    $(this).parent().find("div.arrow-down").remove();
});

$("#sidebar div").click(function() {
    $("#real_0").hide();
    $(".content_sub").hide();
    var menuClass = $(this).attr('class');
    menuClassP = menuClass.split(" ");
    $("#real_" + menuClassP[1]).fadeIn('slow');
});

我正在尝试添加一个功能,该功能将仅突出显示与 当前 *活动* 内容相对应的菜单项。

写这个的最好方法是什么?我现在的代码可以变得更干净吗?

【问题讨论】:

  • 您可以使用rel 属性来保存您需要的类。而不是拆分字符串。会干净一些

标签: jquery menu


【解决方案1】:

添加

$(this).addClass('selected').siblings().removeClass('selected');

在您的点击处理程序中,并在您的 CSS 中定义一个 selected 类来定义突出显示样式..

这会将selected 类添加到当前单击的元素(假设这是活动内容),并将其从其兄弟元素中删除(侧边栏中的其他 div)

【讨论】:

  • 我认为这行得通,但唯一的冲突是我还有另一个添加悬停效果的功能,它会在悬停时删除“选定”应用的样式。我添加了上面的代码。
  • @MG1,使用不同的类名。您可以使用.selected, .highlight {foo:bar; ...} 在css 中定义多个类,并为click 应用highlight,为hover 应用selected ..
【解决方案2】:

您可以通过将每个菜单项的“data-menuid”之类的内容设置为属性来使用 jquery 数据属性。这样就不用拆分类名来使用了。

<li data-menuid="1">menu</li>

$("#sidebar div").click(function() {
    $("#real_0").hide();
    $(".content_sub").hide();
    $("#real_" + $(this).data("menuid")).fadeIn('slow');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    相关资源
    最近更新 更多