突出显示当前页面的导航菜单

Posted

技术标签:

【中文标题】突出显示当前页面的导航菜单【英文标题】:highlight the navigation menu for the current page 【发布时间】:2011-06-05 07:33:26 【问题描述】:

在有一些导航链接的页面中,我希望当前页面的链接被高亮显示,就像这样:

链接“HTML Attributes”被突出显示(粗体),因为此链接将指向当前页面。

我知道这可以手动实现(只是突出显示相应的链接,但有什么聪明的方法吗?动态自动突出显示正确的链接?

【问题讨论】:

【参考方案1】:

我通常会在服务器端(即 php、ASP.NET 等)处理这个问题。这个想法是,当页面加载时,服务器端控制机制(可能通过设置 CSS 值)反映在客户端看到的结果 html 中。

【讨论】:

你能提供更多细节吗?【参考方案2】:

您可以使用 javascript 解析您的 DOM,并使用与第一个 h1 标记相同的标签突出显示链接。但我认为这是矫枉过正 =)

最好设置一个包含页面标题的变量,并使用它在相应的链接处添加一个类。

【讨论】:

嗨哈巴克斯;请记住,您正在回答一个老问题,因此原始问题的作者可能很久以前就以一种或另一种方式解决了他们的问题。为了使您的答案有用,对于在网站上搜索类似问题的解决方案的其他读者来说,这应该是一个很好的答案;所以我建议添加更多的解释和细节,也许还有官方文档的链接,以真正证明为什么这种技术是解决这类问题的最佳方法。【参考方案3】:

您可以将页面正文的 id 设置为代表当前页面的某个值。然后为菜单中的每个元素设置一个特定于该菜单项的类。在您的 CSS 中,您可以设置一个规则来特别突出显示菜单项...

这可能没有多大意义,所以这里有一个例子:

<body id="index">
<div id="menu">
 <ul>
  <li class="index"     ><a href="index.html">Index page</a></li>
  <li class="page1"     ><a href="page1.html">Page 1</a></li>
 </ul>
</div> <!-- menu -->
</body>

在 page1.html 中,您可以将正文的 id 设置为:id="page1"

最后在你的 CSS 中你有如下内容:

#index #menu .index, #page1 #menu .page1 
  font-weight: bold;

您需要更改每个页面的 ID,但 CSS 保持不变,这很重要,因为 CSS 经常被缓存并且可能需要强制刷新才能更新。

它不是动态的,但它是一种简单的方法,您可以使用 PHP 或类似工具从模板文件中 include 菜单 html。

【讨论】:

听起来不错,很简单。但是如何提醒每一页的id呢?在服务器端? 对于我自己的一个网站,页面是静态 html - 这种方法只是使更新更简单(因为菜单在包含的文件中,如果我添加新页面,我只需要更改一次)。但是,是的,您需要某种方式在服务器端设置正文 ID。你如何做到这一点很大程度上取决于你如何运行你的网站。例如,我的 Wordpress 博客使用了一个主题,该主题根据正在查看的页面在 body 标记中设置 class 这种方法意味着你必须在每个视图中都有一个 body 元素。不是很优雅。您几乎可以肯定需要 JS 动态地执行此操作。 jQuery 让它变得非常简单。看看我下面的答案。 @kevinx007 - “视图”是什么意思?正文 tag,虽然在技术上是可选的,但通常包含在格式良好的 html 中,因此在大多数情况下它应该不是问题,除非您正在制作原型并决定不使用标签明确指定元素。 关于视图,我指的是 MVC 视图。在有一个基本布局包含您的正文标签并且您有不同的视图但没有正文标签的情况下。但我的回答可能对技术过于具体,问题仅与 HTML 有关。【参考方案4】:

在我看来,您需要当前代码作为“.menu-current css”,我问的是同样的代码,它就像一个魅力,你可以尝试这样的东西可能仍然是一些配置

a:link, a:active 
    color: blue;
    text-decoration: none;


a:visited 
    color: darkblue;
    text-decoration: none;


a:hover 
    color: blue;
    text-decoration: underline;


div.menuv 
    float: left;
    width: 10em;
    padding: 1em;
    font-size: small;



div.menuv ul, div.menuv li, div.menuv .menuv-current li 
    margin: 0;
    padding: 0;
    list-style: none;
    margin-bottom: 5px;
    font-weight: normal;


div.menuv ul ul 
    padding-left: 12px;


div.menuv a:link, div.menuv a:visited, div.menuv a:active, div.menuv a:hover 
    display: block;
    text-decoration: none;
    padding: 2px 2px 2px 3px;
    border-bottom: 1px dotted #999999;


div.menuv a:hover, div.menuv .menuv-current li a:hover 
    padding: 2px 0px 2px 1px;
    border-left: 2px solid green;
    border-right: 2px solid green;


div.menuv .menuv-current 
    font-weight: bold;


div.menuv .menuv-current a:hover 
    padding: 2px 2px 2px 3px;
    border-left: none;
    border-right: none;
    border-bottom: 1px dotted #999999;
    color: darkblue;

【讨论】:

【参考方案5】:
<script id="add-active-to-current-page-nav-link" type="text/javascript">
    function setSelectedPageNav() 
        var pathName = document.location.pathname;
        if ($("nav ul li a") != null) 
            var currentLink = $("nav ul li a[href='" + pathName + "']");
            currentLink.addClass("active");
        
    
    setSelectedPageNav();
</script>

【讨论】:

如果您在子目录中工作,这可能不起作用,但您的菜单使用了相对链接 - 例如,如果您的页面位于 example.com/site/,那么它对您的所有用户都完全有效链接为a.htmlb.html 等,但路径名为/site/a.html,不匹配? 如果您的菜单链接是完整路径而不是相对路径,这将/确实可以正常工作。它只是使用 jquery 选择器来查找与您在 nav 元素内的页面具有相同链接的元素。为什么说它不会起作用?在上面的例子中,只要你的链接元素 href="/site/a.html" 就可以了。 正如你提到的,它需要你的路径是完整的,而不是相对的。这本身不是问题,但可能会使开发变得痛苦。如果在 Windows 上开发,例如,C:\webdev\site1,并将文件直接加载到浏览器而不是通过配置的 httpd,document.location.pathname 给出例如/C:/webdev/site1/index.html。依赖完整路径名可能会导致各种问题,而相对路径也可以正常工作,同时提供可移植性。【参考方案6】:

CSS类在这里

<style type="text/css">
.mymenu

    background-color: blue;
    color: white;

.newmenu

    background-color: red;
    color: white;

</style>

让你的 HTML 像这样,设置 url 为 id

  <div class="my_menu" id="index-url"><a href="index-url">Index</a></div>
  <div class="my_menu" id="contact-url"><a href="contact-url">Contac</a></div>

这里写javascript,把这段javascript放在HTML代码之后。

    function menuHighlight() 
       var url = window.location.href;
       $('#'+tabst).addClass('new_current');
    
    menuHighlight();

【讨论】:

【参考方案7】:

我通常使用一个类来实现这一点。实现任何东西都非常简单,导航链接、超链接等。

在您的 CSS 文档中插入:

.current,
nav li a:hover 
   /* styles go here */
   color: #e00122;
   background-color: #fffff;

这将使列表项的悬停状态具有红色文本和白色背景。将该类当前附加到“当前”页面上的任何链接,它将显示相同的样式。

我是你的 HTML 插入:

<nav>
   <ul>
      <li class="current"><a href="#">Nav Item 1</a></li>
      <li><a href="#">Nav Item 2</a></li>
      <li><a href="#">Nav Item 3</a></li>
   </ul>
</nav>

【讨论】:

【参考方案8】:

请看以下内容:

以下是有效的:

1.) 顶部菜单按钮可见并正确突出显示

2.) 菜单按钮在点击顶部菜单之前不可见

以下是需要改进的地方:

1.) 当点击子菜单时,寻找新页面以保持所选子菜单打开(我将突出显示所选子菜单按钮以进一步说明导航)

请在此处查看代码: http://jsbin.com/ePawaju/1/edit

或在这里: http://www.ceramictilepro.com/_6testingonly.php#

<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

我需要把这个脚本放在 head 部分吗?最好的地方在哪里?

<div class="left">
<nav class="vmenu">
    <ul class="vnavmenu">
        <li data-ref="Top1"><a class="hiLite navBarButton2" href="#">Home</a>
        </li>
    </ul>
    <ul class="Top1 navBarTextSize">
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub1</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub2</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub3</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub4</a>
        </li>
    </ul>
    <ul class="vnavmenu">
        <li data-ref="Top2"><a class="hiLite navBarButton2" href="#">Repairs</a>
        </li>
    </ul>
    <ul class="Top2 navBarTextSize">
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">1sub1</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">2sub2</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">3sub3</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">4sub4</a>
        </li>
    </ul>
</nav>

JQuery 对我来说是新的,任何帮助将不胜感激:) 变量子菜单;

$('.vnavmenu li').click(function () 
var elems = $('.vmenu ul:not(.vnavmenu)').length;
var $refClass = $('.' + $(this).attr('data-ref'));
var visible = $refClass.is(':visible');

$('.vmenu ul:not(.vnavmenu)').slideUp(100, function () 

    if (elems == 1) 
        if (!visible) $refClass.slideDown('fast');
    

    elems--;
);

if (visible) $('#breadcrumbs-pc').animate(
    'margin-top': '0rem'
, 100);
else $('#breadcrumbs-pc').animate(
    'margin-top': '5rem'
, 100);
);

【讨论】:

【参考方案9】:

CSS:

.topmenu ul li.active a, .topmenu ul li a:hover 
    text-decoration:none;
    color:#fff;
    background:url(../images/menu_a.jpg) no-repeat center top;

JavaScript:

<script src="JavaScript/jquery-1.10.2.js" type="text/javascript"></script> 

<script type="text/javascript">
    $(function() 
        // this will get the full URL at the address bar
        var url = window.location.href;

        // passes on every "a" tag
        $(".topmenu a").each(function() 
            // checks if its the same on the address bar
            if (url == (this.href)) 
                $(this).closest("li").addClass("active");
                //for making parent of submenu active
               $(this).closest("li").parent().parent().addClass("active");
            
        );
    );        
</script>

HTML代码:

<div class="topmenu">
    <ul>
        <li><a href="Default.aspx">Home</a></li>
        <li><a href="NewsLetter.aspx">Newsletter</a></li>
        <li><a href="#">Forms</a></li>
        <li><a href="#">Mail</a></li>
        <li><a href="#">Service</a></li>
        <li style="border:none;"><a href="#">HSE</a></li>
        <li><a href="#">MainMenu2</a>
           <ul>
              <li>submenu1</li>
              <li>submenu2</li>
              <li>submenu3</li>
          </ul>
       </li>
    </ul>
</div>

【讨论】:

这就是我要找的。感谢分享:) 这是我会投票两次的答案之一。谢谢。 谢谢!很棒的简单干净的解决方案【参考方案10】:

JavaScript:

<script type="text/javascript">
    $(function()  
        var url = window.location;
        $('ul.nav a').filter(function() 
            return this.href == url;
        ).parent().parent().parent().addClass('active');
    );   
</script>

CSS:

.active
    color: #fff;
    background-color: #080808;

HTML:

<ul class="nav navbar-nav">
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="true"><i class="glyphicon glyphicon-user icon-white"></i> MY ACCOUNT <span class="caret"></span></a>
                            <ul class="dropdown-menu" role="menu">
                                <li>
                                    <?php echo anchor('myaccount', 'HOME', 'title="HOME"'); ?>
                                </li>
                                <li>
                                    <?php echo anchor('myaccount/credithistory', 'CREDIT HISTORY', 'title="CREDIT HISTORY"'); ?>
                                </li>
                          </ul>
                     </li>
</ul>

【讨论】:

【参考方案11】:

我更喜欢使代码尽可能简短明了,并避免使用任何外部文件(包括 jquery)。 所以这就是我在研究了几个主题后为自己最终得到的结果——使用纯 Javascript 和 CSS,不需要 jquery。

在菜单完成后(在关闭 ul、div 等之后)立即放置 javascript 代码 - 来自 sn-p 的代码应该在 &lt;script&gt;Copy code here&lt;/script&gt; 之间 这将允许在加载菜单后立即执行脚本。 如果您想在页面加载时将其作为函数调用,则链接仅在加载所有元素(包括图像)后才会更改 - 将此代码放在一个函数中,在页面加载时调用它,代码本身放在结束标记之前,如所以:

<script>
    function highlightCurrentURL() 
      var a = document.getElementById("navig").getElementsByTagName("a");
      for (var i = 0; i < a.length; i++) 
        if (a[i].href.split("#")[0] == document.location.href.split("#")[0]) 
          a[i].className = "current";
        
      
    
    // 
    window.onload = function() 
      highlightCurrentURL();
    
</script>

// restrict search to a parent with specific ID (main), rather than search in the whole document
var a = document.getElementById("navig").getElementsByTagName("a");
console.log("Current URL: ", document.location.href.split("#")[0]);
console.log("Links found in HTML: ");
for (var i = 0; i < a.length; i++) 
  // for debugging you can check all found URLs in console (accessible in development mode) and delete next line after debugging
  console.log(a[i].href);
  // strip off any local (withing page) anchors (symbol "#" and what follows after)
  if (a[i].href.split("#")[0] == document.location.href.split("#")[0]) 
    // add a class to the matched link (<a>), define it in CSS
    a[i].className = "current";
  
nav#navig a.current 
  color: red;
<nav id="navig">
  <ul>
    <li><a href="/url1">url1 name</a></li>
    <li><a href="/url2">url2 name</a></li>
    <li><a href="/url3">url3 name</a></li>
    <li><a href="https://stacksnippets.net/js#test_page_anchor">Test link matching current URL</a></li>
  </ul>
</nav>

【讨论】:

这个问题是 10 年前在旧版 html 上提出的 [link](#comment68994017_4626537) - 正如文斯在评论中提到的,这是一个老问题,任何进一步的更新都是针对像我这样的人,而不是主题启动者。所以更新应该更普遍,对其他人有帮助。我的不是这样吗?我是在这里写作的新手,如果我做错了什么,请道歉。只是更具体地说明我的错误,这样我就不会重复了。 10 年前我的方式不可用吗?【参考方案12】:

您可以使用 PHP 或 Jquery 以各种方式实现此功能。以下是我在项目中的实现方式。

<?php 
    //set a default value when the page is not an active page  

    $dashboard_active=$profile_active=$home_active='inactive_page';
    
    //get the Name of the current page;
    //in simple php set the NAME of the php file similar to the link variable
    //example set page name as home if you are going to print the variable $home/$home_active

    $page = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);

    //OR
    //in Laravel

    $page=Route::currentRouteName();
    
    //OR
    //send page value from the controller
    

    $$page."_active" = 'active_page';

//the above method will change the value of the current active page variable

        ?>

在 html 中打印 php 数据

<ul class="nav navbar-nav ">
<li ><a href="www.p.com/dashboard"><span class=" <?php echo $dashboard_active ?> ">  Dashboard</span></a></li>
<li ><a href="www.p.com/profile"><span class=" <?php echo $profile_active ?>"> Profile</span></a></li>
<li ><a href="www.p.com/home"><span class=" <?php echo $home_active ?>">Home</span></a></li>
</ul>

你也可以用 Jquery 做到这一点

<script>
    //with jquery
$(function()
    //works when your href is an absolute href instead of relative href
        $('a').each(function()
            if ($(this).prop('href') == window.location.href)                 
                $(this).children('span').addClass('active_page');  
                //to make the link only active
                $(this).addClass('active_page');   
                //to make the list active 
                $(this).panrent('li').addClass('active_page');   
            
        );
    );
</script>

在你需要添加的 CSS 中

<style>    
.active_page:hover,.inactive_page:hover

  background-color: rgb(218, 119, 5)!important;
    color: white;

.active_page

  background-color: green!important;
    color: white!important;      


.inactive_page

    color:#fff;    

</style>

【讨论】:

以上是关于突出显示当前页面的导航菜单的主要内容,如果未能解决你的问题,请参考以下文章

如何正确构建突出当前页面的导航菜单

重新加载页面后如何突出显示导航栏中的活动菜单项

如何根据活动页面突出显示导航菜单项(具有:: after伪元素)。

突出显示当前所选导航菜单项的背景

带有 Jekyll 和 Liquid 的排序导航菜单

如何在batmanjs中实现导航菜单