请考虑以下示例:(live demo here)
HTML:
<div class="wrapper">
<div city_id="1" class="odd">Street Name #1 in city 1</div>
<div city_id="3" class="even">Street Name #2 in city 3</div>
<div city_id="2" class="odd">Street Name #3 in city 2</div>
<div city_id="1" class="even">Street Name #4 in city 1</div>
<div city_id="1" class="odd">Street Name #5 in city 1</div>
<div city_id="3" class="even">Street Name #6 in city 3</div>
<div city_id="2" class="odd">Street Name #7 in city 2</div>
<div city_id="3" class="even">Street Name #8 in city 3</div>
<div city_id="1" class="odd">Street Name #9 in city 1</div>
</div>
<select>
<option value="">Please select...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
CSS:
.odd {
background-color: #777;
}
.even {
background-color: #aaa;
}
JS:
$(function() {
$("select").change(function() {
var city_id = $("option:selected", this).val();
$("div[city_id]").each(function() {
$(this).toggle($(this).attr("city_id") == city_id);
});
});
});
即使隐藏了某些行,我仍希望保持交替着色。
使用纯CSS可以实现这一点吗?
如果不是,你会怎样使用Javascript / jQuery?
答案 0 :(得分:3)
这是一个简单的解决方案。在所选索引更改时动态更改行的类
$(function() {
$("select").change(function() {
var city_id = $("option:selected", this).val();
$("div[city_id]").each(function() {
$(this).toggle($(this).attr("city_id") == city_id);
}).filter(":visible") ///filter the visible ones
.attr("class",function(index,$class){
///if you don't want to miss out the other classes
return index%2 == 0 ? $class.replace("odd","even") : $class.replace("even","odd");
});
});
});
答案 1 :(得分:2)
您可以使用CSS:
.wrapper div:nth-child(even) { background-color: #777; }
.wrapper div:nth-child(odd) { background-color: #aaa; }
但是,它不会考虑隐藏的行。为此,您需要更加限制div
选择器:
.wrapper div.visible:nth-child(even) { background-color: #777; }
.wrapper div.visible:nth-child(odd) { background-color: #aaa; }
然后,您只需确保所有可见元素都具有visible
类。
答案 2 :(得分:2)
你需要从javascript设置类奇数或甚至通过遍历项目,如果它们是可见的替代类
答案 3 :(得分:0)
使用jquery,您可以在更改事件中使用:
$('.wrapper div:visible:even').css({
'background-color': '#777'
});
$('.wrapper div:visible:odd').css({
'background-color': '#aaa'
});
完整代码
$("select").change(function() {
var city_id = $("option:selected", this).val();
$("div[city_id]").each(function() {
$(this).toggle($(this).attr("city_id") == city_id);
});
$('.wrapper div:visible:even').css({
'background-color': '#777'
});
$('.wrapper div:visible:odd').css({
'background-color': '#aaa'
});
});
这样它会将背景颜色设置为仅考虑可见行