Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

CSS:

.menuItem{
  display:inline;
  height:30px;
  width:100px;
  background-color:#000;
}

Javascript:

$('.menuItem').hover( function(){
     $(this).css('background-color', '#F00');
},
function(){
     $(this).css('background-color', '#000');
});

EDIT: I forgot to say that I had reasons not to want to use the css way.

And I indeed forgot to check if the DOM was loaded.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
138 views
Welcome To Ask or Share your Answers For Others

1 Answer

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');
   });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...