change background color of li using jquery

前端 未结 4 1332
情书的邮戳
情书的邮戳 2021-01-22 23:56

I want to change the color of li which contains anchor when the mouse go over it, I make like this

 
相关标签:
4条回答
  • 2021-01-23 00:30

    If you're wanting a nice hover effect then you'll want jquery, you'll also need jquery-color.js, the code is below:

    <script type="text/javascript">
        $(function () {
            $('#menu .dummyclass').mouseover(function () {
                $(this).animate({
                    backgroundColor: '#FF0000'
                }, 50, function () { });
            });
        });
        $(function () {
            $('#menu .dummyclass').mouseleave(function () {
                $(this).animate({
                    backgroundColor: '#000000'
                }, 600, function () { });
            });
        });
    </script>
    

    HTML Markup:

    <div id="menu">
        <ul>
            <li class="dummyclass">Home</li>
            <li class="dummyclass">Fixtures</li>
            <li class="dummyclass">Results</li>
            <li class="dummyclass">Tables</li>
            <li class="dummyclass">Constitution</li>
            <li class="dummyclass" style="border-right: none;">Contact Us</li>
        </ul>
    </div>
    

    CSS:

    #menu ul li .dummyclass {
        /*Dummy class to aid hovering with jQuery*/
    }
    
    0 讨论(0)
  • 2021-01-23 00:36

    Do it like this:

    $("a[id='son']").hover(function(){
       $(this).closest("li.sonItem").css("background-color","black");  
    });
    

    NOTE: This will work ok, however you should never have more than 1 element with the same id (you can, but it's a very, very bad practice), it'd be better if you use a class, for example class="son", and your selector would be $("a.son").

    Cheers

    0 讨论(0)
  • 2021-01-23 00:40

    Id is unique so dont repeat, u can use in class

    $(document).ready(function(){
      $(".son").hover(function(){
        $(".sonItem").css("background-color","black");
        },function(){
        $(".sonItem").css("background-color","white");
        });
    });
    
    <ul id="SonsItemList">
         <li class="sonItem"><a class="son" href="#" >son 1</a></li>
          <li class="sonItem"><a class="son" href="#" >son 2</a></li>        
    </ul>
    
    0 讨论(0)
  • 2021-01-23 00:47

    You don't need any JavaScript at all. You can use CSS:

    li.sonItem:hover 
    {
        background-color: black;
    }
    
    0 讨论(0)
提交回复
热议问题