change color of selected menu tab

后端 未结 3 1539
一向
一向 2020-12-21 12:14

I grabbed this snippet from another question:



        
相关标签:
3条回答
  • 2020-12-21 12:31

    @wsanville

    What about the problem of double-clicking the same tab?

    If i remove a bottom-border from a tab (indicating the selected one) when clicked on a tab, that's fine. But when i click it again, it should just stay like that (no bottom border), but because of the toggle now it looks like you haven't selected the tab but you are still there.

    0 讨论(0)
  • 2020-12-21 12:48

    You can actually greatly simplify your Javascript for this. This should achieve your desired effect.

    <script type="text/javascript">
        $(document).ready(function() {
            $("div.content ul li a")
             .mouseover(function() {
                 $(this).addClass('mouseover');
             })
             .mouseout(function() {
                 $(this).removeClass('mouseover');
             });
    
            $("div.content ul li a").click(function(e) {
                e.preventDefault(); //prevent the link from actually navigating somewhere
                $(this).toggleClass("clicked");
                $("div.content ul li a").not(this).removeClass("clicked"); //remove the clicked class from all other elements
            });
        });
    </script>
    

    The Javascript here will do the following:

    • Add the "mouseover" class when you hover a link
    • Remove the "mouseover" class when you no longer hover a link
    • When you click a link, it will toggle the "clicked" class and remove it from any other link that may have had the class - this will restore your other tabs to their "normal" state.
    0 讨论(0)
  • 2020-12-21 12:51

    It is possible to achieve what you are looking for using just CSS:

    ul li a {background-color: white;}
    ul li a:hover {background-color: black;}
    ul li a:focus {background-color: black;}
    

    Demo

    0 讨论(0)
提交回复
热议问题