将特定的类/id应用于菜单上的当前页面(PHP) [英] Apply a specific class/id to current page on menu (PHP)
本文介绍了将特定的类/id应用于菜单上的当前页面(PHP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的菜单:
<div id="blahblah" style="blahblah">
<a href="http://domain.com/folder/biography"><img style="blahblah" src="blahblahblahblah"></a>
<a href="http://domain.com/folder/contacts"><img style="blahblah" src="blahblahblahblah"></a>
<a href="http://domain.com/folder/gallery"><img style="blahblah" src="blahblahblahblah"></a>
<a href="http://domain.com/folder/dontknow"><img style="blahblah" src="blahblahblahblah"></a>
</div>
我想要一些可以自动将class ="current"添加到我当前所在的页面的工具.链接(如您在上面的代码中可以看到的)就像domain.com/folder/biography或domain .com/folder/contacts,因此没有.php/.html等.
I'd like to have something that automatically adds a class="current" to the page I'm currently in. Links (as you can see in the code above) are like domain.com/folder/biography or domain.com/folder/contacts, so without .php/.html, etc.
我尝试过:
<div id="blahblah" style="blahblah">
<a <?php if (strpos($_SERVER['PHP_SELF'], 'biography')) echo 'class="current"';?> href="http://domain.com/folder/biography"><img style="blahblah" src="blahblahblahblah"></a>
<a <?php if (strpos($_SERVER['PHP_SELF'], 'contacts')) echo 'class="current"';?> href="http://domain.com/folder/contacts"><img style="blahblah" src="blahblahblahblah"></a>
...
...
</div>
但是它不起作用...带有strops的解决方案似乎是可行的,可能是我做错了..:P
But it doesn't work... the solution with strops seems viable, probably I'm doing it wrong.. :P
推荐答案
您应该:
- 用
!== false
检查strpos()
的结果. - 使用
$_SERVER['REQUEST_URI']
而不是$_SERVER['PHP_SELF']
. - 将代码包装在函数中.
- check the result of
strpos()
with!== false
. - Use
$_SERVER['REQUEST_URI']
rather than$_SERVER['PHP_SELF']
. - Wrap the code inside a function.
类似这样的东西:
<?php
function get_current($name) {
if (strpos($_SERVER['REQUEST_URI'], $name) !== false)
echo 'class="current"';
}
?>
<div id="blahblah" style="blahblah">
<a <?php get_current('biography') ?> href="http://domain.com/folder/biography"><img style="blahblah" src="blahblahblahblah"></a>
<a <?php get_current('contacts') ?> href="http://domain.com/folder/contacts"><img style="blahblah" src="blahblahblahblah"></a>
...
...
</div>
这篇关于将特定的类/id应用于菜单上的当前页面(PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文