How to add a CSS class depending on URL path?

后端 未结 3 539
渐次进展
渐次进展 2021-01-26 01:56

How can I add an CSS class to an div depending on what path I am on, including that it should not mather if I had # in it?

相关标签:
3条回答
  • 2021-01-26 02:12

    none of these worked for me. this works:

    <script type="text/javascript">
        jQuery(document).ready(function($){
            // Get current url
            // Select an a element that has the matching href and apply a class of 'active'.     Also prepend a - to the content of the link
            var url = window.location.href;
            $('.menu a[href="'+url+'"]').addClass('active');
        });
    </script>
    

    menu structure:

    <div class="menu">
        <a href="#" class="menu-element">001</a>
        <a href="#" class="menu-element">002</a>
    </div> 
    

    source: http://www.paulund.co.uk/use-jquery-to-highlight-active-menu-item

    0 讨论(0)
  • 2021-01-26 02:20

    This is the simple code for create Dynamic active menu for website by using JavaScript & JQuery.

    <style>
    .myactive{
         background-color:#F7A751;
        }
        </style>
    
    <script type="text/javascript">
    $(function () {
    var url = window.location.pathname; 
    var activePage = url.substring(url.lastIndexOf('/') + 1);
        activePage === '' ?  $('#home').addClass("myactive") : $('#home').removeClass("myactive") ; // for active index page
        activePage === 'about-us' ? $('#about').addClass("myactive") : $('#about').removeClass("myactive") ; //active about us 
        activePage === 'who-we-are' ? $('#info').addClass("myactive") : 
        $('#info').removeClass("myactive") ; 
    });
    </script>  
    
    #HTML Part....
     <li id="home"><a href="#">Home</a></li>
     <li id="about"><a href="#">About</a></li>
    
    0 讨论(0)
  • 2021-01-26 02:21
    jQuery(function($){
       switch(window.location.hash){
          case "vs":  $(".popup").addClass("class1"); break;
          case "bod":  $(".popup").addClass("class2"); break;
          case "ptf":  $(".popup").addClass("class3"); break;
       }
    });
    
    0 讨论(0)
提交回复
热议问题