2013-07-29 225 views
2

基本上,当我将鼠标悬停在表格中的一行上时,我希望该行的背景颜色更改为“黑色”,并且特定的单元格或td我正在盘旋以更改到'红'。JQuery更改表格单元格和行背景颜色悬停

即,当悬停时发生两个事件。我知道如何做到这一点,但不是两者。

这可能使用jQuery吗?

Thx给大家他们的贡献,我已经复制了你们所有人。

+2

有没有你不能只用css理由吗? http://jsfiddle.net/4STXa/ –

+0

如果你可以给一个单元格打上颜色,那么在同一个函数中,为什么不能获得父行并为它着色呢?像'$(this).addClas(“red”); $(this).closest(“tr”)。addClass(“black”);' – TCHdvlp

回答

3

简单的CSS是不够的:

tr:hover{ 
background-color:red 
} 

td:hover{ 
background-color:blue 
} 

http://jsfiddle.net/nRuXn/1/

+0

Thx是忘记了旧的CSS。那就是诀窍。 – Nuvolari

+0

经过我自己的一些经验,我开始思考只有当有人谈论“悬停”,“mouseover-mouseout”,“mouseenter-mouseleave” – rps

1

如果行和单元格都在同一个容器中,则可以将mouseover事件附加到该容器并修改处理程序中的子级。

2

一些类添加到你想成为红认为,TD(让调用类的rdClass')和行“blkClass”:

<table> 
<tr class='rdClass'> 
<td> 
     1 
</td> 
<td class='blkClass'> 
     2 
</td> 
<td> 
     3 
</td> 
</tr> 
</table> 

$(document).ready(function() 
{ 
    $(".rdClass").mouseover(function() 
    { 
     $(this).css("background-color", "red"); 
    }); 

    $(".blkClass").mouseover(function() 
    { 
     $(this).css("background-color", "black"); 
    }); 
}); 
2

添加悬停监听到所有的行和TD的,增加了并删除一个类,然后使用CSS为行和单元格对该类进行不同的样式设置。

Working Demo

jQuery的

$('tr, td').hover(function() { 
    $(this).addClass('highlight'); 
}, function() { 
    $(this).removeClass('highlight'); 
}); 

CSS

tr.highlight { 
    background-color: red; 
} 

td.highlight { 
    background-color: black; 
} 
1
$("td").hover(function(){ 
    $(this).css("background-color", "red"); 
    $(this).parrent('tr').css("background-color", "black"); 
}); 
3
$('td').hover(function() { 
    $(this).parent().children().css("background-color", "black"); 
    $(this).css("background-color", "red") 
}); 

$('tr').mouseleave(function() { 
    $(this).children('td').css("background-color", "white");// or whatever 
}); 
相关问题