Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

php - Add active CSS class to menu item

I have this category menu. When I click on a category menu item, it opens the category page and what I need it to add the 'active' Bootstrap class on the menu item that was selected (clicked).

How can I do it?

<?php      
 $cat = "SELECT * FROM category WHERE cat_parent_id = :value ORDER BY cat_id ASC"; 
   $stmt = $con->prepare($cat);
   $stmt->bindValue(':value', 1, PDO::PARAM_STR);
      $stmt->execute(); 
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
          extract($row);
             $name_cat = str_replace("-"," ", $cat_name);
             $name_under = str_replace(" ","-", $cat_name);
             ?>     
               <li><a class="dropdown-item" href="<?php echo $home_url . 
                $cat_id."/".strtolower($name_under);?>.html"><?php echo strtoupper($name_cat); ?></a> 
                 </li>
<?php } ?>  
question from:https://stackoverflow.com/questions/65942425/add-active-css-class-to-menu-item

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Going an extra step on the comment above from @El_Vanja:

Figure out the current url with the following code:

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

Then add that condition when you're forming the link:

<li<?php if($home_url == $actual_link echo ' class="active"';?>><a class="dropdown-item" href="<?php echo $home_url . 
            $cat_id."/".strtolower($name_under);?>.html">
            <?php echo strtoupper($name_cat); ?></a></li>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...