我只想在使用 php 打开页面时将一个名为"active"的css
类添加到我的导航链接中。
在我的网站上,内容已经分解成各个组成部分。这些组件被分离、组织,并使用一个索引文件重新组合在一起。(网站引导程序文件)实际上,我正在使用php模块化此网站。
我的导航类似于此代码 -
...
<li>
<a href="index.php?p=dashboard">Dashboard</a>
</li>
<li>
<a href="index.php?p=page-two">Page Two</a>
</li>
<li>
<a href="index.php?p=page-three">Page Page Three</a>
</li>
...
这就是我的索引.php的样子——
// Validate what page to show:
if (isset($_GET['p'])) {
$p = $_GET['p'];
} elseif (isset($_POST['p'])) { // Forms
$p = $_POST['p'];
} else {
$p = NULL;
}
// Determine what page to display:
switch ($p) {
case 'dashboard':
$page = 'dashboard.inc.php';
$page_title = 'Control Panel';
break;
case 'page-three':
$page = 'page-three.inc.php';
$page_title = 'Page Three';
break;
case 'page-two':
$page = 'page-two.inc.php';
$page_title = 'Page Two';
break;
// Default is to include the main page.
default:
$page = 'login.inc.php';
$page_title = 'Control Panel Login';
break;
} // End of main switch.
// Make sure the file exists:
if (!file_exists('./modules/' . $page)) {
$page = 'login.inc.php';
$page_title = 'Control Panel Login';
}
include('./includes/header.html');
include('./modules/' . $page);
include('./includes/footer.html');
我不知道如何将active
css 类动态添加到我的链接中。 希望有人可以帮助我。
谢谢。
使用 $_SERVER['PHP_SELF']
将当前文件与要加载的页面进行比较。
如果它们相等:
case 'dashboard':
$page = 'dashboard.inc.php';
$page_title = 'Control Panel';
$class == ($page == $p) ? 'active' : '';
break;
并将此类添加到 HTML 中。
<li class="<?php echo $class;?>">
...
如果你对 JS/Jquery 解决方案没问题,这里是
网页代码:
<ul class="menu">
<li>
<a href="index.php?p=dashboard">Dashboard</a>
</li>
<li>
<a href="index.php?p=page-two">Page Two</a>
</li>
<li>
<a href="index.php?p=page-three">Page Page Three</a>
</li>
</ul>
JS代码:
function getParameterByName(name) {
name = name.replace(/['[]/, "''[").replace(/[']]/, "'']");
var regex = new RegExp("[''?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/'+/g, " "));
}
$(document).ready(function(){
var PageName = getParameterByName('p');
$("li a[href*='"+PageName+"']").addClass("active");
});
工作示例在这里http://jsfiddle.net/naveenkumarpg/f16yqrpx/3/