I wan\'t to change the background color of a div dynamicly using the following HTML, CSS and javascript. HTML:
-
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)
-
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)
-
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)
-
Always keep things easy and simple by creating a class
.bcolor{ background:#F00; }
THEN USE THE addClass() & removeClass() to finish it up
讨论(0)