简体   繁体   中英

Change the color of selected menu item using css

I want to highlight currently opening page using css styles.here is my html code

<ul class="nav" id="nav">
  <li id="home">
    <a href="home.html" data-id="home" target="ifrm">Home</a>
    <ul>
     <li><a href="item1.html" target="ifrm">item1</a></li>
     <li><a href="item2.html" target="ifrm">item2</a></li>
     <li><a href="item3.html" target="ifrm">item3</a></li>
    </ul>
  </li>
  <li id="skill"><a href="skill.html" data-id="skill" target="ifrm">Skill</a></li>
  <li id="research"><a href="research.html" data-id="research"    target="ifrm">Research</a></li>
  <li id="link"><a href="link.html" data-id="link" target="ifrm">Link</a></li>
</ul>
<iframe name="ifrm"></iframe>

It should be only change the font and background color of menu list ,witch page is loading in the iframe.

 $(function(){ $('li a').click(function(){ $('li a').each(function(a){ $( this ).removeClass('selectedclass') }); $( this ).addClass('selectedclass'); }); $('ul a').click(function(){ $('ul a').each(function(a){ $( this ).removeClass('selectedclass') }); $( this ).addClass('selectedclass'); }); }); 
 li a.selectedclass { color:red; background-color:blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="nav" id="nav"> <li id="home"><a href="home.html" data-id="home" target="ifrm">Home</a> <ul> <li ><a href="item1.html" target="ifrm">item1</a></li> <li ><a href="item2.html" target="ifrm">item2</a></li> <li ><a href="item3.html" target="ifrm">item3</a></li> </ul> </li> <li id="skill"><a href="skill.html" data-id="skill" target="ifrm">Skill</a></li> <li id="research"><a href="research.html" data-id="research" target="ifrm">Research</a></li> <li id="link"><a href="link.html" data-id="link" target="ifrm">Link</a></li> </ul> <iframe name="ifrm"></iframe> 

You need to define first a class that has required styles and then click of anchor tag remove this class from all the class and then add it to the clicked anchor tag.

Add this code in your file

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
    $("a").click(function(){
        $("a").css("color","BLUE"); // change this color to default one
        $( this ).css( "color", "RED" ); 
    });
</script>

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