You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现根据当前访问页面动态切换导航a标签的active高亮类

你的实现思路是可行的,但存在几个需要修正的问题:

  • 首页<a>标签的class属性中手动多写了一个active类,会导致无论当前是否访问首页,首页都会始终高亮,需要删掉这个手动添加的类
  • 函数参数currect_page存在拼写错误,建议修正为更表意的命名
  • 如果你的站点使用了伪静态规则隐藏.php后缀,或者页面存在多级目录路径(比如archives页面在/pages子目录下),basename($_SERVER['PHP_SELF'])只能获取当前执行脚本的文件名,无法匹配路径层级,会出现判断错误
  • 你当前示例中的<a>标签href属性写的是#index这类锚点值,要替换为你实际的页面路径

优化后方案

如果你的站点URL存在多级路径,或者用了伪静态,推荐用$_SERVER['REQUEST_URI']做匹配,兼容性更强:

<?php
function get_active_class($target_path) {
    // 提取当前访问的URI,剔除?后面的查询参数
    $current_uri = strtok($_SERVER['REQUEST_URI'], '?');
    // 精准匹配路径的场景直接用==判断即可,需要模糊匹配子路径可以用str_contains
    return $current_uri === $target_path ? 'active' : '';
}
?>

<div class="right-nav">
    <a href="/metrics/website/index" class="<?= get_active_class('/metrics/website/index') ?>">Home</a>
    <a href="/metrics/website/pages/archives" class="<?= get_active_class('/metrics/website/pages/archives') ?>">Archives</a>
</div>

如果你的所有页面都在根目录,没有多级路径,也没有使用伪静态,原逻辑稍作修改即可使用:

<?php
function get_active_class($target_page) {
    $current_page = str_replace(".php", "", basename($_SERVER['PHP_SELF']));
    return $target_page === $current_page ? 'active' : '';
}
?>

<div class="right-nav">
    <a href="/metrics/website/index" class="<?= get_active_class('index') ?>">Home</a>
    <a href="/metrics/website/pages/archives" class="<?= get_active_class('archives') ?>">Archives</a>
</div>

额外注意

你当前的CSS选择器写的是.topnav a.active,但导航容器的类是right-nav,如果没有父级元素使用topnav类,高亮样式不会生效,建议将选择器修改为.right-nav a.active,或者给导航容器加上topnav类。

内容的提问来源于stack exchange,提问作者Mads Sander Høgstrup

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:45:04