Dynamically change CSS of link based on current page

前端 未结 4 834
长发绾君心
长发绾君心 2020-11-29 12:56

I have the following links at the top of my web page:

 
相关标签:
4条回答
  • 2020-11-29 13:23

    You can check each link and see if it matches the current location. This can be more or less advanced depending on your needs, but something like:

    var loc = window.location.pathname;
    
    $('.icyLink').find('a').each(function() {
      $(this).toggleClass('active', $(this).attr('href') == loc);
    });
    

    Then style the active class in your CSS:

    .icyLink a.active{color:#fff}
    
    0 讨论(0)
  • 2020-11-29 13:27

    Set a unique body id in each page and an id on each menu item then:

    #home-page #home-menu,
    #history-page #history-menu { background: blue; } // Etc....
    
    0 讨论(0)
  • 2020-11-29 13:35

    You are looking for jQuery .css or .addClass functions.

    0 讨论(0)
  • 2020-11-29 13:43
    <ul class="icyLink">
    
      <li><a class="nav1" href="index.html">The World of Icengale</a></li>
      <li><a class="nav1" href="history.htm">History of Icengale</a></li>
      <li><a class="nav1" href="calendar.htm">Time & Calendar of Icengale</a></li>
    
    </ul>
    <script>
    $(document).ready(function(){
       $("a.nav1").click(function () {
          // switch all tabs off
          $(".active").removeClass("active");
          // switch this tab on
          $(this).addClass("active");
       });
    });
    </script>
    

    css

    .active{background-image: url('../images/blue3.jpg');color:#fff;}
    
    0 讨论(0)
提交回复
热议问题