jQuery hover and class selector

后端 未结 10 1702
半阙折子戏
半阙折子戏 2020-12-10 00:56

I wan\'t to change the background color of a div dynamicly using the following HTML, CSS and javascript. HTML:


      
      
10条回答
  • 2020-12-10 01:30

    I prefer foxy's answer because we should never use javascript when existing css properties are made for the job.

    Don't forget to add display: block ; in .menuItem, so height and width are taken into account.

    edit : for better script/look&feel decoupling, if you ever need to change style through jQuery I'd define an additional css class and use $(...).addClass("myclass") and $(...).removeClass("myclass")

    0 讨论(0)
  • 2020-12-10 01:33

    This can be achieved in CSS using the :hover pseudo-class. (:hover doesn't work on <div>s in IE6)

    HTML:

    <div id="menu">
       <a class="menuItem" href=#>Bla</a>
       <a class="menuItem" href=#>Bla</a>
       <a class="menuItem" href=#>Bla</a>
    </div>
    

    CSS:

    .menuItem{
      height:30px;
      width:100px;
      background-color:#000;
    }
    .menuItem:hover {
      background-color:#F00;
    }
    
    0 讨论(0)
  • 2020-12-10 01:35

    Your code looks fine to me.

    Make sure the DOM is ready before your javascript is executed by using jQuery's $(callback) function:

    $(function() {
       $('.menuItem').hover( function(){
          $(this).css('background-color', '#F00');
       },
       function(){
          $(this).css('background-color', '#000');
       });
    });
    
    0 讨论(0)
  • 2020-12-10 01:37

    Always keep things easy and simple by creating a class

    .bcolor{ background:#F00; }

    THEN USE THE addClass() & removeClass() to finish it up

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