我正在检查用户当前页面,并将.css类应用于正确的菜单项。
我的问题是,我怎样才能做到最好?目前,我有这个:
$currentpage = $_SERVER['PHP_SELF'];
if($currentpage == "/prefs.php") $active = "active";
if($currentpage == "/acc.php") $active = "active";
if($currentpage == "/forum.php") $active = "active";
<a href='acc.php' title='Sync' aria-hidden='true' class='{$active} tipTip'>
<a href='acc.php' title='Sync' aria-hidden='true' class='{$active} tipTip'>
<a href='forum.php' title='Statistics' aria-hidden='true' class='{$active} tipTip'>
但是这只会将active
类添加到所有锚元素中。
答案 0 :(得分:4)
简单的方法是在HTML中添加if语句:
<?php $currentpage = $_SERVER['PHP_SELF']; ?>
<a href='acc.php' title='Sync' aria-hidden='true' class='<?php if($currentpage == "/prefs.php") echo "active "; ?>tipTip'>
<a href='acc.php' title='Sync' aria-hidden='true' class='<?php if($currentpage == "/acc.php") echo "active "; ?>tipTip'>
<a href='forum.php' title='Statistics' aria-hidden='true' class='<?php if($currentpage == "/forum.php") echo "active "; ?>tipTip'>
虽然这可能不如其他选项那么可读。
答案 1 :(得分:2)
为变量指定不同的名称:
$currentpage = $_SERVER['PHP_SELF'];
if($currentpage == "/prefs.php") $active1 = "active";
if($currentpage == "/acc.php") $active2 = "active";
if($currentpage == "/forum.php") $active3 = "active";
<a href='acc.php' title='Sync' aria-hidden='true' class='{$active1} tipTip'>
<a href='acc.php' title='Sync' aria-hidden='true' class='{$active2} tipTip'>
<a href='forum.php' title='Statistics' aria-hidden='true' class='{$active3} tipTip'>
答案 2 :(得分:1)
<?php
$currentpage = $_SERVER['PHP_SELF'];
echo "<a href='prefs.php' title='Sync' aria-hidden='true' class='" . ($currentpage == '/prefs.php' ? 'active' : '') . " tipTip'>
<a href='acc.php' title='Sync' aria-hidden='true' class='" . ($currentpage == '/acc.php' ? 'active' : '') . " tipTip'>
...";
如果您不喜欢这样,也可以使用switch() { case '': break; }
设置。
答案 3 :(得分:0)
获得自我功能:
function getSelf($dir=""){
if($dir==""){ $dir = $_SERVER['PHP_SELF']; }
$self = explode("/",$dir);
return $self[count($self)-1];
}
然后像菜单的分隔符:
<?php
$cls="";
$quick = "index.php||other_page.php||other_page2.php";
$stack = explode("||",$quick);
if(in_array(getSelf(), $stack)){ $cls = " active"; } else { $cls = ""; }
?>
然后class="<?php echo $cls; ?>"
答案 4 :(得分:0)
有一种略有不同的方法,但它也需要JavaScript(我知道你没有在标签中列出JavaScript,但你仍然可能觉得这很有用)。 诀窍是使页面名称响应(修改的)DOM元素ID或类。
// or just make a simple function that strips the name from the $currentpage
// if the names are consistent like in your example
if ($currentpage == "/prefs.php") $id="prefs";
elseif ($currentpage == "/acc.php") $id="acc";
elseif ($currentpage == "/forum.php") $id="forum";
然后,进行JavaScript调用以找到正确的锚元素并为其分配“active”类。这是一个jQuery示例:
var active = '<?php echo $id; ?>';
$('a .' + active).addClass('active'); // for class name
$('#' + active).addClass('active'); // for id, you get the point
这只是一个简单的例子,但我认为如果您使用JavaScript,它可能会有所帮助并使您的代码更具可读性。