CSS:设置表中所选行的颜色 [英] CSS: set color for selected row in a table
问题描述
我需要向我的表中添加以下功能:当用户点击一行(选择它)时,该行标记为颜色#FFCF8B(与悬停相同
)。我尝试#newspaper-b tbody tr.selected td
,但它不工作。
I need to add the following feature to my table: when the user clicks on a row (selects it), the row is marked with the color #FFCF8B (the same as hover
). I tried #newspaper-b tbody tr.selected td
, but it does not work.
#newspaper-b {
border-collapse: collapse;
border-color: #B7DDF2;
border-style: solid;
border-width: 1px;
font-family: Arial,Helvetica,sans-serif;
font-size: 11px;
margin: 0;
text-align: left;
width: 480px;
}
#newspaper-b th {
background: none repeat scroll 0 0 #EBF4FB;
border-color: lightgray;
font-size: 11px;
font-weight: bold;
padding: 15px 10px 10px;
}
#newspaper-b tbody tr td {
background: none repeat scroll 0 0 #FFFFFF;
}
#newspaper-b td {
border-top: 1px dashed #FFFFFF;
color: #000000;
padding: 10px;
}
#newspaper-b tbody tr:hover td {
background: none repeat scroll 0 0 #FFCF8B;
color: #000000;
}
#newspaper-b tbody tr.selected td {
background: none repeat scroll 0 0 #FFCF8B;
color: #000000;
}
推荐答案
示例 http: //jsfiddle.net/thebabydino/KzVfy/
我使用jQuery作为示例,因此只有很少的代码:
I used jQuery for the example, so there is very little code:
$("tr").click(function(){
$(this).addClass("selected").siblings().removeClass("selected");
});
当然,
只是为了变化,我做了另一个版本。 这个不使用库(没有jQuery,没有Mootools,没有YUI,没有Dojo,等等),并选择多行。在 http://jsfiddle.net/thebabydino/nY5jj/ 可以看到,点击时取消选中所选行的变体再次 http://jsfiddle.net/thebabydino/nY5jj/1/
Just for variation, I did another version. This one uses no library (no jQuery, no Mootools, no YUI, no Dojo, and so on...) and selects multiple rows. Can be seen at http://jsfiddle.net/thebabydino/nY5jj/ with a variation that unselelects a selected row when clicking on it again http://jsfiddle.net/thebabydino/nY5jj/1/
JavaScript是:
The JavaScript is:
var trs = document.querySelectorAll("tr");
for(var i = 0; i < trs.length; i++){
trs[i].addEventListener("click", function(){this.className += " selected";});
}
第二次单击时取消选择所选行: p>
To unselect a selected row when clicking on it a second time :
var trs = document.querySelectorAll("tr");
for(var i = 0; i < trs.length; i++){
trs[i].addEventListener("click", function(){
var cn = this.className, thc = " selected", start_idx = cn.indexOf(thc);
if(start_idx == -1) cn += thc;
else cn = cn.replace(thc,"");
this.className = cn;
});
}
这篇关于CSS:设置表中所选行的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!