CSS 属性未显示用于使用 PHP 的活动导航元素



我知道标题有点模糊,对不起。我不能用一句话轻易表达出来。所以,无论如何。

我目前正在开发我的个人网站。我想让当前页面的 nav 元素以某种颜色突出显示。为此,我想使用它:

<a href="index.php" class="nav-item" <?php if($current =='home'){echo 'class = "active"';}?>>Home</a>

其他页面也是如此。但是,"class = "active" 甚至没有应用于 a 标签。我的索引页面包含以下内容:

$current = "home";

活动类的 CSS 如下所示:

.active{
background-color: #fdfdfd !important;
color: #3D1c4B;
}

我真的不知道我做错了什么。是我缺少什么,还是这只是我不能用 a 元素做的事情?

这是导航的外观

您不能有多个类标签,您已经有一个无法添加第二个的类标签。试试这个:

<a href="index.php" class="nav-item<?= $current == 'home' ? ' active' : '' ?>">Home</a>

您的 HTML 无效,并且会呈现:<a href="index.php" class="nav-item" class="active">- 它有两个class属性(不合法(。 像下面这样修改你的 PHP,将两个类放在同一个属性中:

<a href="index.php" class="nav-item<?php if($current =='home'){echo ' active';}?>">Home</a>

您在<a>标签中两次写入class属性

<a href="index.php" class="nav-item" <?php if($current =='home'){echo 'class = "active"';}?>>Home</a>

它应该是这样的

<a href="index.php" class="nav-item <?php if($current =='home'){echo 
' active'; }?>" >Home</a>

在变量中获取类并像这样使用它:

<?php 
$className = '';
if($current =='home'){
$className = 'active';
echo "<a href='index.php' class='nav-item " . $className . "'>Home</a>";
?>

首先,我看到您使用:

<a href="index.php" class="nav-item" <?php if ( $current =='home' ) echo 'class = "active"'; ?> >Home</a>

是错误的,因为你会得到class="nav-item" class="active", - 相反,你需要写:

<a class="nav-item <?php if ( $current =='home') echo 'active'; ?>" href="index.php">Home</a>

您的代码将添加 2 个类,以便只有一个类将应用于您的标签。

试试这样。

<a href="index.php" class="nav-item <?php if($current =='home'){echo 'active';}?>">Home</a>

最新更新