<html>
<style>
.highlight{
background-color: pink;
}
.over{
background-color: red;
}
.odd{
background-color: lightgrey;
}
.even{
background-color: gray;
}
</style>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$('.c').addClass('highlight');
$('.a').addClass('odd');
$('.b').addClass('even');
});
</script>
</head>
<body>
<h2>2: Zebra Striping Demo</h2>
<table width="200" border="1">
<caption><a href="#">UP</a> Zebra Striping Demo <a href="#">DN</a></caption>
<tr class = "a"><td>January</td> <td>February</td><td>March</td></tr>
<tr class = "b"><td>April</td><td>May</td><td>June</td></tr>
<tr class = "c"><td>July</td><td>August</td><td>September</td></tr>
<tr class = "a"><td>October</td><td>November</td><td>December</td</tr>
<tr class = "b"><td>Monday</td><td>Tuesday</td><td>Wednesday</td></tr>
<tr class = "a"><td>Thursday</td><td>Friday</td><td>Saturday</td></tr>
<tr class = "b"><td>Spring</td><td>Summer</td><td>Fall</td></tr>
</table>
</body>
<script>
$("tr").hover(function(){
$(this).addClass("over");
}, function() {
$(this).removeClass("over");
});
</script>
</html>
&#13;
我在这段代码中尝试做的是在悬停时对.over css类进行颜色更改。所以基本上,使用悬停功能,它不会改变所有行的颜色。只有c类行在悬停时才会被更改。关于如何解决这个问题的建议?
答案 0 :(得分:3)
这是由于正在应用CSS的 order 。
首先,任何带有.highlight
的tr都会获得背景颜色(粉红色)。然后任何.over
的tr都会得到它的背景颜色(替换.highlight
),依此类推。请注意,.even
和.odd
是最后一次。
您的两个选项是重新排序CSS声明(如@ j08691的答案)或使.over
的样式为!important
.over{
background-color: red !important;
}
答案 1 :(得分:2)
只需更改CSS规则的顺序,以便.over
为最后且具有优先权。
$(document).ready(function() {
$('.c').addClass('highlight');
$('.a').addClass('odd');
$('.b').addClass('even');
});
$("tr").hover(function() {
$(this).addClass("over");
}, function() {
$(this).removeClass("over");
});
.highlight {
background-color: pink;
}
.odd {
background-color: lightgrey;
}
.even {
background-color: gray;
}
.over {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<h2>2: Zebra Striping Demo</h2>
<table width="200" border="1">
<caption><a href="#">UP</a> Zebra Striping Demo <a href="#">DN</a>
</caption>
<tr class="a">
<td>January</td>
<td>February</td>
<td>March</td>
</tr>
<tr class="b">
<td>April</td>
<td>May</td>
<td>June</td>
</tr>
<tr class="c">
<td>July</td>
<td>August</td>
<td>September</td>
</tr>
<tr class="a">
<td>October</td>
<td>November</td>
<td>December</td>
</tr>
<tr class="b">
<td>Monday</td>
<td>Tuesday</td>
<td>Wednesday</td>
</tr>
<tr class="a">
<td>Thursday</td>
<td>Friday</td>
<td>Saturday</td>
</tr>
<tr class="b">
<td>Spring</td>
<td>Summer</td>
<td>Fall</td>
</tr>
</table>