简体   繁体   中英

Different Color in The Active Navigation Button

I would like to change the background color of the menu button when I'm on the page

在此处输入图片说明

This is my code:

HTML

<ul>
  <li><a class="active" href="index.php">Home</a></li>
  <li><a href="news.php">News</a></li>
  <li><a href="contact.php">Contact</a></li>
  <li><a href="about.php">About</a></li>
</ul>

CSS

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover:not(.active) {
    background-color: #111;
}

.active {
    background-color: #4CAF50;
}

I know that I have to use Javascript but I don't now the code to change the class when the link is active.

It would be better to use PHP for this. On each page add a variable with the name of the page assigned to it eg

<?php $page = "News"; ?>

Then you can add conditional statements that will add an active class to the navigation link that relates to the page you are viewing eg

<ul>
  <li><a <?php echo ($page == "Home") ? "class='active'" : ""; ?> href="index.php">Home</a></li>
  <li><a <?php echo ($page == "News") ? "class='active'" : ""; ?> href="news.php">News</a></li>
  <li><a <?php echo ($page == "Contact") ? "class='active'" : ""; ?> href="contact.php">Contact</a></li>
  <li><a <?php echo ($page == "About") ? "class='active'" : ""; ?> href="about.php">About</a></li>
</ul>

If you don't recognise the PHP code, it is just a shorthand version of an if statement.

制作一个不同的CSS页面,然后将其链接到该页面,然后复制并粘贴所有内容。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM