在导航栏中突出显示当前页面 [英] Highlight Current Page in Navigation Bar

查看:151
本文介绍了在导航栏中突出显示当前页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着试探主题行中提出的问题.所以下面是我要完成的工作的HTML和jQ.

I tried to give a shot at the problem posed in the subject line. So below is my HTML and jQ for what I'm trying to accomplish.

html


<ul class="topnav1">
   <li class="highlight">
      <a  href="index.php">Home</a>
   </li>
   <li>
      <a  href="testimonials_page.php">Testimonials</a>
   </li>
   <li>
      <a href="services.php">Services</a>
   </li>
   <li>
      <a href="contact_page.php">Contact  Us</a>
   </li>
</ul>

jQ


<script type='text/javascript'>
//Menu highlights.
$(document).ready(function(){
   var pathname =  (window.location.pathname.match(/[^\/]+$/)[0]);
   $(".topnav1 li a").each(function() {
      if ($(this).attr('href')==pathname) {
         $("li.highlight").removeClass("highlight");
         $(this).parent().parent().addClass("highlight");
      }
   });
   $("li.highlight"').parents().each(function(){
      if ($(this).is("li")){
         $(this).addClass("highlight");
      }
   });
});
</script>

这个想法是从其默认列表项中删除突出显示的类,并将其分配给其href属性与当前url匹配的列表项.我必须承认我不是最擅长编写匹配模式,所以我对如何仅将部分网址与href属性进行匹配感到困惑,而且我不确定这就是为什么我的代码不正确的原因工作(突出显示保留在主菜单项上,不适用于其他菜单项).有什么想法吗?

The idea is to remove the highlighted class from its default list item, and assign it to the list item whose href attribute matches the current url. I must admit I'm not the best at programming matching patterns, so I'm kind of at a loss as to how to match only part of the url with the href attribute and I'm not sure that's why my code isn't working( the highlight is retained on the home menu item and isn't applied to the others). Any ideas?

推荐答案

我建议以下内容:

// in real life use: var curURL = document.location.toString();
var curURL = 'http://fiddle.jshell.net/_display/testimonials_page.php';

$('.topnav1 li.highlight').removeClass('highlight');
$('.topnav1 li a').each(
    function(){
        if (curURL.indexOf(this.href) != -1){
            $(this).closest('li').addClass('highlight');
        }
    });

JS Fiddle演示.

参考:

jQuery,来自 jQuery API :

jQuery, from the jQuery API:

这篇关于在导航栏中突出显示当前页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆