简体   繁体   中英

jquery not changing the selected menu item text color

i added jquery to change selected menu item color when selected,the jquery changes the background color of the item perfectly but it does not change the color of the text /. following is my html and jquery and css:

css:

.highlight
{
     color:orange;
}

HTML:

<div class="menuWrapper">
     <ul id="navBar">
           <li class="highlight"><a href="aboutus.aspx"><span>ABOUT US</span></a></li>
           <li><a href="ourwork.aspx"><span>OUR WORK</span></a> </li>
           <li><a href='#'><span>CONTACT US</span></a></li>
     </ul>

</div>

SCRIPT:

     <script type="text/javascript">
           var str = location.href.toLowerCase();
           $("#navBar li a").each(function () {
                 if (str.indexOf($(this).attr("href").toLowerCase()) > -1) {
                       $("li.highlight").removeClass("highlight");
                       $(this).parent().addClass("highlight");
                 }
           });
           $("li.highlight").parents().each(function () {
                 if ($(this).is("li")) {
                       $(this).addClass("highlight");
                 }
           });
     </script>

please help me to solve this problem,thank you

.highlight a span
{
 color:orange;
}

Just add anchor tag in css. Because always anchor tag takes higher priority with its default blue color.

or just

  .highlight a
{
 color:orange;
}

Add your highlight class to a so that text will be highlighted.

or

li.highlight a{
    color: orange;
}

I added your code to a JS fiddle: http://jsfiddle.net/grammar/ttk4qkze/

The problem lies in the default browser styles for links. Your CSS only targets the items with a class of highlight , which in this case is the <li> . The <a> will not inherit the color property from its parent automatically, so you have to set it yourself.

.highlight,
.highlight a {
  color: orange;
}

Additionally, I don't think you need the second each() loop. parents() of the <li> element will never be another <li> .

set a class for span which will contain the menu item text, then use ":active" css state selector to set the styles when selected a menu item

.menu_item_txt:active{
     color: red;
}

<ul id="navBar">
        <li class="highlight"><a href="aboutus.aspx"><span class="menu_item_txt">ABOUT US</span></a></li>
        <li><a href="ourwork.aspx"><span>OUR WORK</span></a> </li>
        <li><a href='#'><span>CONTACT US</span></a></li>
</ul>

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