简体   繁体   中英

Active menu - attribute the class “active” to the link in it's own page

I want to add an active menu witch attributes the class "active" to the link in it's own page.

The code is in a separate file called "header.php".

I've tried many ways and script codes, but can't make it work, so i'm asking for help in this.

The code i have for the menu is the following:

<div class="wrapper row1">
<header id="header" class="hoc clear"> 

  <div id="rl1" class="fl_left">
    <h1><a href="/"><img src="images/logo"></a></h1>
  </div>
<div class="topnav" id="myTopnav">
  <a href="/" class="active">Início</a>
  <a href="sobre_nos.php">Sobre Nós</a> 
  <a href="servicos.php">Serviços</a>
  <a href="contactos.php">Contactos</a>
  <a href="#"><i class="fa fa-facebook-f"></i></a>
  <a href="#"><i class="fa fa-linkedin"></i></a>
      <a href="javascript:void(0);" class="icon" onclick="myFunction()">
      <i class="fa fa-bars"></i>
      </a>
</header>

You want to have the selected link highlighted?

Add below script. This wraps the clicked item into a span with a preselected class. I have modified it to fit your HTML .

$(document).on('click', '.topnav a', function(e) {
  $('.topnav .menuselect a').unwrap(  )
  $(this).wrap("<span class='menuselect'></span>");
});

Assume your have a $var variable.

<nav>
    <a href="contactos.php" class="<?php echo ($var == "contact" ? "active" : "")?>">Contactos</a>
</nav>
<a href="/" class="getClass('/')">Início</a>
<a href="sobre_nos.php" class="getClass('sobre_nos.php')">Sobre Nós</a> 
<a href="servicos.php" class="getClass(..)">Serviços</a>
<a href="contactos.php" class="getClass(..)">Contactos</a>

implement getClass :

function getClass(path){
    if(path == window.location.href.split('/').pop()){
        return "active";
    }
    return "";
}

Define $page variable at the top of every file bedore including header.php and now check in header.php for that page. Consider below example for sobre_nos.php. Do this for every page.

header.php

<div class="wrapper row1">
<header id="header" class="hoc clear"> 

  <div id="rl1" class="fl_left">
    <h1><a href="/"><img src="images/logo"></a></h1>
  </div>

<div class="topnav" id="myTopnav">
  <a href="/" class="active">Início</a>
  <a href="sobre_nos.php" <?= ($page === 'sobre_nos')?'class="active"' : '';?>>Sobre Nós</a> 
  <a href="servicos.php">Serviços</a>
  <a href="contactos.php">Contactos</a>
  <a href="#"></i></a>
  <a href="#"></i></a>
      <a href="javascript:void(0);" class="icon" onclick="myFunction()">
      <i class="fa fa-bars"></i>
      </a>
</header>

sobre_nos.php

$page = 'sobre_nos'; 

<?php include 'header.php'; ?>

.....Your content

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