在子页面上也突出显示父菜单

时间:2015-10-04 06:28:37

标签: javascript jquery html css menu

我有一个简单的多级菜单和一个脚本,用于突出显示菜单项,无论是父菜单还是子菜单。

在下面的示例中,当我在子页面上时,它只会更改子页面的颜色,而我还想更改颜色或它的父项。

我尝试了一些东西,但它没有按预期工作。

到目前为止我所拥有的http://gdata.youtube.com/feeds/api/users/channelname/uploads?orderby=published。 如果不起作用,请参阅以下代码段:



jQuery(document).ready(function() {
  var url = window.location.href;
  $('#cssmenu a[href="' + url + '"]').addClass('active-menu');

  // Will also work for relative and absolute hrefs
  $('#cssmenu a').filter(function() {
    return this.href == url;
    $(this).parents("li a").addClass('active-menu');
  }).addClass('active-menu');

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cssmenu">
  <div id="menu-button"></div>
  <ul>
    <li><a href="/en/about-us/">About Us</a>
    </li>
    <li class="has-sub">
      <span class="submenu-button"></span><a href="#">Gallery </a>
      <ul>
        <li><a href="/en/photo-gallery/" class="active-menu">Photo Gallery</a>
        </li>
        <li><a href="/en/video-gallery">Video Gallery</a>
        </li>
        <li><a href="/en/instagram-gallery">Instagram Gallery</a>
        </li>
      </ul>
    </li>
    <li><a href="/en/news/">News</a>
    </li>
    <li><a href="/en/contact/">Contact</a>
    </li>
  </ul>
</div>
&#13;
&#13;
&#13;

更新

这是我的新代码,但是这样可以保留其他链接:

&#13;
&#13;
$('#cssmenu a').filter(function() {
  $(this).parents("li.has-sub").find('a:first').addClass('active-menu');
  return this.href == url;
}).addClass('active-menu');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cssmenu">
  <div id="menu-button"></div>
  <ul>
    <li><a href="/en/about-us/">About Us</a>
    </li>
    <li class="has-sub">
      <span class="submenu-button"></span><a href="#">Gallery </a>
      <ul>
        <li><a href="/en/photo-gallery/" class="active-menu">Photo Gallery</a>
        </li>
        <li><a href="/en/video-gallery">Video Gallery</a>
        </li>
        <li><a href="/en/instagram-gallery">Instagram Gallery</a>
        </li>
      </ul>
    </li>
    <li><a href="/en/news/">News</a>
    </li>
    <li><a href="/en/contact/">Contact</a>
    </li>
  </ul>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

我想,这就是你追求的目标。

var $menu = $("#cssmenu");
//Get the anchor based on the page URL
var $current = $menu.find('a').filter(function() {
    return location.href.indexOf(this.href) > -1;
    //Or (whatever works)
    //return location.href === this.href;
});
//Add it's parent's anchor
$current = $current.add($current.closest("li.has-sub").find(' > a'));
//Set the desired class
$current.addClass('active-menu');

以下是同一行的a demo