我有一个这样的菜单:
<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等。
我尝试过:
<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
答案 0 :(得分:3)
你应该:
strpos()
检查!== false
的结果。$_SERVER['REQUEST_URI']
而不是$_SERVER['PHP_SELF']
。这样的事情:
<?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>
答案 1 :(得分:1)
如果位置为0,那么它将在PHP中评估为FALSE。您应该具体检查返回值,即&gt; = 0。
答案 2 :(得分:1)
而不是strpos()
,你可以试试这个:
<?php $current = basename($path, ".php"); ?>
<a href="blahblah"<?php if ($current == 'biographies') echo ' class="current"'; ?> />
$current
是当前文件的名称,没有.php
扩展名。