jQuery悬停效果在表
问题描述:
我是jQuery的新手,我试图让我的桌上悬停效果,但我不知道如何。 我只想让文字变红,然后在焦点丢失时再次移除红色。jQuery悬停效果在表
这是我到目前为止有:
<script type="text/javascript">
$(function() {
$('tr').hover(function() {
$(this).css('color', 'red')
});
});
</script>
<table border="1">
<tr>
<th>ID</th>
<th>name</th>
</tr>
<tr>
<td>#1</td>
<td>ole</td>
</tr>
<tr>
<td>#2</td>
<td>jeffrey</td>
</tr>
<tr>
<td>#3</td>
<td>collin</td>
</tr>
<tr>
<td>#4</td>
<td>eve</td>
</tr>
</table>
答
您需要在悬停时添加处理程序。 见这里:http://jsfiddle.net/bF9xy/ 文档这里:http://api.jquery.com/hover/
$(function() {
$('tr').hover(function() {
$(this).css('color', 'red')
},function() {
$(this).css('color', 'black')
}
);
});
答
.hover()在jQuery函数有两个参数:用于在事件的一个鼠标功能和用于将鼠标从第二功能:
$('dom element').hover(function()
{
//your code for mouse over
}, function()
{
//your code for mouse out
});
PS:一般来说,在像你这样的情况下,最好改变元素的类而不是css属性本身。使用.addClass()和.removeClass()。通过这种方式,将来可以更容易地使用悬停效果,只需更改CSS而不是javascript即可。
答
<style type="text/css">
.highlight { background-color:red; }
<style>
<script>
$(
function()
{
$("table>tr").hover(
function()
{
$(this).addClass("highlight");
},
function()
{
$(this).removeClass("highlight");
}
)
}
)
</script>
答
小解决方法:
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$('tr').hover(function() {
$(this).css('color', 'red')
});
$('tr').mouseout(function() {
$(this).css('color', 'black')
});
});
</script>
</head>
<body>
<table border="1">
<tr>
<th>ID</th>
<th>name</th>
</tr>
<tr>
<td>#1</td>
<td>ole</td>
</tr>
<tr>
<td>#2</td>
<td>jeffrey</td>
</tr>
<tr>
<td>#3</td>
<td>collin</td>
</tr>
<tr>
<td>#4</td>
<td>eve</td>
</tr>
</table>
</body>
</html>/
答
由于款式通常比红色文字更复杂,你可能会考虑走这条路:
$(function() {
$('tr').hover(function() {
$(this).toggleClass('redHover')
}, function() {
$(this).toggleClass('redHover')
});
});
redHover会像
<style>
.redHover{
color:red;
}
</style>
然后你c改变样式而不重写你的jQuery。
你的代码是完美的,最好使用'.addClass' – diEcho 2011-03-05 14:48:47