将当前css应用于PHP中的导航

时间:2014-09-30 18:38:02

标签: php html css

我正在使用PHP构建的页面的动态标头,我正在尝试将当前的CSS应用于所选页面。我可以通过在html中定义类current来实现这一点,但这不适用于动态头。

这是我的php头文件我的代码有什么问题。据我所知,php语句应该找出当前页面并应用当前的css,但事实并非如此。

先谢谢你的帮助:)。我的网站是:http://wonx.dk/phpintergrated/index.php

<?php
function get_current($title) {
  if (strpos($_SERVER['REQUEST_URI'], $title) !== false)
    echo 'class="current"';
}
?>


<a href="index.html"><img class="logo" src="img/logofinal.svg"  alt="Devil Sheep Logo" /></a>

<label for="menuon">
<img src="img/menu.svg" alt="MENU"></label>
<input type="checkbox" id="menuon">

<nav>
      <ul class="topmenu">
        <li><a href="index.php" title="Home" >Home</a></li> <!--Sets the home tab to on meaning it is selected.-->
        <li><a href="aboutme.php" title="About Me">About Me</a><!--Whitespace causes problems with display:inline-->
           <ul class="submenu">
            <li class="aboutdropdown"><a href="aboutme.php" title="About Me">About Me</a></li>
            <li><a href="portfolio.php" title="Portfolio">Portfolio</a></li>
            <li><a href="photogallery.php" title="Photo Gallery">Photo Gallery</a></li>
            </ul>
          </li>
        <li><a href="recipe.php" title="Recipe">Recipe</a></li>
        <li><a href="song.php" title="Song">Song</a></li>
        <li><a href="cv.php" title="CV">CV</a></li>
        <li><a href="experiments.php" title="Experiments">Experiments</a></li>
        <li><a href="contact.php" title="Contact Me">Contact Me</a></li>
      </ul>
</nav>

3 个答案:

答案 0 :(得分:1)

您的菜单项数量有限。

声明包含所有菜单项的数组

 $current['index.php'] = "";
 .
 .
 .
 $current['contact.php'] = "";
 $temp = $current;
 foreach($temp AS $key => $value)
 {
   if (strpos($_SERVER['REQUEST_URI'], $key) !== false)
    $current[$key] = 'class="current"';
 }

现在转到html

  <li <?php echo $current["index.php"]?>><a href="index.php" title="Home" >Home</a></li>
 .
 .
 .
 <li <?php echo $current["contact.php"]?>><a href="contact.php" title="Contact Me">Contact Me</a></li>

在 。 。 。 意味着冲洗并重复。

享受!

答案 1 :(得分:0)

你必须把类放在元素本身上,比如:

<li><a href="index.php" title="Home" <?=get_current('home')?> >Home</a></li>

答案 2 :(得分:0)

如果你想为链接指定另一个类,或者有人在标题中使用CapiTalS,会发生什么?

function get_current($title) {
  $uri = strtolower($_SERVER['REQUEST_URI']);
  if (strpos($uri, $title) !== false)
    return  'current'; //-- Don't echo in a function, return something
}

并在您的HTML中

<li>
  <a href="index.php" title="Home" class='<?php echo get_current('home');?>' >Home</a>
</li>