我有这个导航,但似乎找不到将.active类添加到当前页的解决方案。有人能帮我吗?
<nav class="menu">
<ul class="menu-ul navigation">
<div class="menu-first">
<li><a href="index.php"><span class="main-title">X-BIKES</span></a></li>
</div>
<div class="menu-second">
<li><a href="index.php?page=events">Events</a></li>
<?php if (empty($_SESSION['user'])): ?>
<li><a href="index.php?page=login">Login</a></li>
<li>/</li>
<li><a href="index.php?page=register">Register</a></li>
<?php else: ?>
<li><a href="index.php?page=logout">Logout</a></li>
<li class="menu-cart">
<a href="index.php?page=cart">Cart (<?php
if(empty($_SESSION['cart'])) {
echo '0';
}else {
echo sizeof($_SESSION['cart']);
};
?>)</a>
</li>
<?php endif; ?>
</div>
</ul>
</nav>
最佳答案
您可以使用$_GET
:
<nav class="menu">
<ul class="menu-ul navigation">
<div class="menu-first">
<li><a href="index.php"><span class="main-title">X-BIKES</span></a></li>
</div>
<div class="menu-second">
<li class="<?php echo $_GET['page'] == "events" ? "active" : ""; ?>" ><a href="index.php?page=events">Events</a></li>
<?php if (empty($_SESSION['user'])): ?>
<li class="<?php echo $_GET['page'] == "login" ? "active" : ""; ?>"><a href="index.php?page=login">Login</a></li>
<li>/</li>
<li class="<?php echo $_GET['page'] == "register" ? "active" : ""; ?>"><a href="index.php?page=register">Register</a></li>
<?php else: ?>
<li class="<?php echo $_GET['page'] == "logout" ? "active" : ""; ?>"><a href="index.php?page=logout">Logout</a></li>
<li class="menu-cart <?php echo $_GET['page'] == "cart" ? "active" : ""; ?>">
<a href="index.php?page=cart">Cart (<?php
if(empty($_SESSION['cart'])) {
echo '0';
}else {
echo sizeof($_SESSION['cart']);
};
?>)</a>
</li>
<?php endif; ?>
</div>
</ul>
</nav>
然后在CSS中,可以更改链接颜色:
.navigation a {
color: blue;
}
.navigation .active a {
color: red;
}
关于javascript - 在当前页面上设置事件类(class),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45959561/