移动子页面/其他页面时,在引导程序中保持当前导航菜单处于活动状态


Stay current nav menu active in bootstrap when move sub page/ other page

我想让菜单导航在访问子页面/其他页面时在 boostrap 中保持活动状态。

这是我在标题菜单上的代码:

    function echoActiveClassIfRequestMatches($requestUri)
     {
       $current_file_name = basename($_SERVER['REQUEST_URI'], ".php");
       if ($current_file_name == $requestUri)
         echo 'class="active"';
    }

>首页

此功能仅在我们访问 parrent 页面时才有效。 如果想要访问子页面,导航菜单不会保持活动状态。例如:如果我们访问 index.php,导航菜单处于活动状态,但如果我们从 index.php 访问子页面,则导航菜单未处于活动状态。当我们访问子页面时,如何激活导航菜单?非常感谢您的回答。

简单的答案是您可以使用

$_SERVER['SCRIPT_NAME']

而不是

$_SERVER['REQUEST_URI']

更长的答案是,您从函数中处理多个内容,这将阻止您重用代码。

请参考以下建议:

<?php
  /**
   * checks if the user called a certain script
   */
  function requestMatches($script_name)
  {
    return (basename($_SERVER['SCRIPT_NAME'], '.php') == $script_name);
  }
  /**
   * identifies the class for a given request 
   */
  function getClassForRequest($script_name)
  {
    return requestMatches($script_name) ? 'active' : '';
  }
?>
<ul class="nav navbar-nav navbar-left">
  <li class="<?=getClassForRequest('table')?>">
    <a href="table.php">Table <span class="sr-only">(current)</span></a>
  </li>
  <li class="<?=getClassForRequest("index")?>">
    <a href="index.php">home <span class="sr-only">(current)</span></a>
  </li>
</ul>

通过将逻辑分离到单独的函数中,您现在可以轻松解决多种情况(如果这种情况的话)。请注意,不需要从函数体回显,因为<?= ?>已经为您这样做了。


最后,我要补充一点,这件事应该完全在客户端处理。下面是一个使用 jQuery 的示例。

<ul class="nav navbar-nav navbar-left" id="custom_menu">
  <li>
    <a href="table.php">Table <span class="sr-only">(current)</span></a>
  </li>
  <li>
    <a href="index.php">home <span class="sr-only">(current)</span></a>
  </li>
</ul>
<script>
$(function() {
    var path = window.location.pathname;
    var item = path.split('/').pop();
    var element = $('#custom_menu a[href="' + item + '"]');
    if (element.length == 0) {
        // no elements match the current request uri
        return false;
    }
    element.parent().addClass('active');
});
</script>

Finnaly,我正在使用此代码来解决我的问题。

function echoActiveClassIfRequestMatches($requestUri)
     {
       $current_file_name = basename($_SERVER['REQUEST_URI'], ".php");
       if ($current_file_name == $requestUri)
         echo 'class="active"';
    }
<!-- menu fuction -->
<ul class="nav navbar-nav navbar-left">
<li id="home" <?=echoActiveClassIfRequestMatches("index")?>><a href="index.php">HOME <span class="sr-only">(current)</span></a></li>
</ul>
<!-- add jquery in each sub page -->
<script src="jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#home').addClass('active');
         // other menu
        //$('#table').addClass('active');
    });
</script>

谢谢。。