简体   繁体   中英

Dynamic Bootstrap 4 Navbar "active" tag

i need to change the "active" class depending on the site you are right now when clicking the header.

Ive seen some examples using a php check if you are on the page "noten.php" and it would change the navbar class to active accordingly, also checked some Javascript like this

$('.navbar-nav .nav-link').click(function(){
$('.navbar-nav .nav-item').removeClass('active');
$(this).addClass('active');

}) but nothing worked

    <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
  <a class="navbar-brand" href="/">Projekt</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarCollapse">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="/">Startseite</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="/noten.php">Noten</a>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Soon</a>
      </li>
    </ul>

We don't know much about your PHP logic, but the implementation may be pretty simple:

<?php
  $uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
  $uri_segments = explode('/', $uri_path);
?>


<li class="nav-item <?php echo 'active page-' . $uri_segments[0]; ?>">
  <a class="nav-link" href="/">Startseite</a>
</li>

For the url http://foobar/first/second will add the class page-first .

Ive found a way.

Adding this at the top of my header include

<?php
$pg = basename(substr($_SERVER['PHP_SELF'],0,strrpos($_SERVER['PHP_SELF'],'.'))); // get file name from url and strip extension

?>

and then adding this to the Navbar itself

          <li class="nav-item <?php if($pg=='index'){?>active<?php }?>">
        <a class="nav-link" href="/">Startseite</a>
      </li>

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