PHP - 根据我所在的页面,更改活动类 [英] PHP - Based on which page I'm on, change the active class

查看:75
本文介绍了PHP - 根据我所在的页面,更改活动类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3页。根据我所在的网页,我想更改活动类别以反映该类别。

I have 3 pages. Based on which page I'm on, I'd like to change the class of active to reflect that.

这3个网页是索引,博客和联系人。每个人都有子页面,像工作有各种项目的各种PHP文件。博客有各种博客文章。联系人只是一个PHP联系表单。

The 3 pages are index, blog, and contact. Each of them have sub-pages as well, like Work has various PHP files for various projects. Blog has various blog posts. Contact is just a PHP contact form.

我想根据用户的身份,移动class =active。

I'd like to, based on what the person is on, move the class="active" around. Right now it's hard-coded on each page.

我的代码是:

<ul class="list-inline" id="menu">
    <li class="active">
        <a href="index.php">work</a>
    </li><!--
    --><li>
        <a href="blog.php">blog</a>
    </li><!--
    --><li>
        <a href="contact.php">contact</a>
    </li><!--
    --><li>
        <a href="#"><img class="social" src="img/icon/icon-facebook.png" alt="facebook"></a>
        <a href="#"><img class="social" src="img/icon/icon-twitter.png" alt="twitter"></a>
    </li>
</ul>


推荐答案

添加此PHP:

<?php #add class .active to current page
   $directoryURL = $_SERVER['REQUEST_URI'];
   $path = parse_url($directoryURL, PHP_URL_PATH);
   $components = explode('/', $path);
   $currentPage = preg_replace("/\\.[^.\\s]{3,4}$/", "", end($components));

   if ($currentPage == "") {
       $currentPage = "index";
   }

   function href($url) {
      global $currentPage;
      $path = explode('/', $url);
      $page = preg_replace("/\\.[^.\\s]{3,4}$/", "", end($path));
      echo 'href="' . $url . '"';

      if ($page == $currentPage) {
         echo 'active';
      }
   }
?>

调整菜单为:

<li><a <?php href('about.php');?>>About</a></li>

*
祝好运

这篇关于PHP - 根据我所在的页面,更改活动类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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