jQuery在hover时改变背景

我有这个代码

HTML

我的jQuery是

jQuery的

 $(document).ready(function(){ $(".aQli").mouseover(function(){ }); $(".aQli").mouseout(function(){ }); }); 

我希望当hover在一个li上时,背景应该是红色,并且从那个li退出时,背景应该返回白色。 我怎样才能做到这一点?

你必须使用jQuery吗?

更“正确”的方法是为您的class级添加hover样式。

 .aQli:hover{ background-color: red; }​ 

请看这里的例子。 http://jsfiddle.net/maurice_butler/5q6QM/

您可以简化此操作以使用.hover():

 $(document).ready(function(){ $(".aQli").hover(function(){ $(this).css("background", "#F00"); }, function(){ $(this).css("background", "#FFF"); }); }); 

第一个函数用于鼠标hover,第二个函数用于mouseout。 .css()函数设置一个CSS属性,在这种情况下是hover元素的背景颜色。

 $(function(){ $(".aQli").on('mouseover', 'li', function(){ //using "on" for optimization this.style.backgroundColor = 'red'; //native JS application }).on('mouseout', 'li', function(){ //chain to avoid second selector call this.style.backgroundColor = 'white'; //native JS application }) }); 

我通过使用jQuery提出了两种方法。 一种方法是使用jQuery直接更改css,使用.css()设置背景颜色。

 //css ul#aQul li{ display : inline-block; padding : 5px; margin : 5px; } //javascript use jQuery $(document).ready(function(){ $(".aQli").mouseover(function(){ $(this).css({ "background-color" : "red", "cursor" : "pointer" }); }); $(".aQli").mouseout(function(){ $(this).css({ "background-color" : "transparent", "cursor" : "default" }); }); });​​ 

另一种方法是在发生hover时使用jQuery添加特定的类属性,并且有一个特定的css规则来更改背景颜色。

 //css, need to specify the state of hover ul#aQul li.hover{ //li elements which have "hover" class cursor:pointer; background-color : red; } //javascript $(document).ready(function(){ $(".aQli").mouseover(function(){ $(this).addClass("hover") //hover, add class "hover" }); $(".aQli").mouseout(function(){ $(this).removeClass("hover"); //hover out, remove class "hover" }); });​ 
 $(document).ready(function(){ $(".box").hover(function(){ $(this).css("background-image", "url(ENETR URL HERE)"); }, function(){ $(this).css("background", "#FFF"); }); }); 
 .box{ width:200px; height:200px; border: 1px solid black; }