Javascript 表1:单元格颜色方案
我在“mytable”表格中有如下菜单:Javascript 表1:单元格颜色方案,javascript,css,Javascript,Css,我在“mytable”表格中有如下菜单: <td id="1" align="center" onclick="clicked(1);"> one </td > <td id="2" align="center" onclick="clicked(2);"> two </td > <td id="3" align="center" onclick="clicked(3);"> three </td> <td id="4
<td id="1" align="center" onclick="clicked(1);"> one </td >
<td id="2" align="center" onclick="clicked(2);"> two </td >
<td id="3" align="center" onclick="clicked(3);"> three </td>
<td id="4" align="center" onclick="clicked(4);"> four </td>
...
javascript:
function clicked(k){
for (x=1; x<5; x++){ // reset all cells
document.getElementById(x).style.background='#4092c4';
document.getElementById(x).style.color='#efefef';
}
// set cell
document.getElementById(k).style.background='#106284';
document.getElementById(k).style.color='#FF004F';
}
单击的函数(k){
对于(x=1;x语法问题,仅为数字的ID不是有效的HTML
您遇到的问题是,当javascript运行时,它会在元素上添加内联样式,而CSS样式无法覆盖内联样式(如果不添加像!important
,这会变得很糟糕)
我会避免在JS中编写样式,只使用它来更改类。因此,创建一个新类,让我们称它为.active
,当您单击一个tablecell时,只需添加该类,并从所有其他类中删除该类
类似(这只是示例,可能需要进行一些调整)
通过这种方式,您可以更好地控制样式规则的“级联”,更具体或更改规则的顺序将给您可能的不同结果
正如fiddle所说,这可能有些过分,但是javascript库使这变得微不足道
我也更改了HTML,因为应该避免对非表格数据使用table
新HTML:
<ul id="mytable">
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
#mytable {
background:#d0d0df;
cursor:pointer;
list-style:none;
padding-left:0;
}
#mytable li {
background:#4092c4;
color:#efefef;
display:inline-block;
margin:2px -2px 2px 2px;
padding:3px;
}
#mytable li:hover {
background:#e0e0e0;
color:#FF004F;
}
#mytable li.active {
background:#106284;
color:#efefef;
}
注意:我已经使用了内联块
对列表项进行了横向定位,您也可以使用浮动
或表格单元格
。这是一篇很好的文章。另外请注意新的活动
类
现在是超级简单jquery(请确保包含jquery库!)
只需确保和使用$(document).ready();
便捷的jQuery链接
你能做一个JSFIDLE吗?顺便说一句,我强烈建议你重新考虑使用表格作为一个简单的菜单。一个风格良好的列表(ul
)从长远来看会为你提供更好的服务。谢谢你-它工作得很好,我也学了一点JSFIDLE!
#mytable {
background:#d0d0df;
cursor:pointer;
}
#mytable td{
background:#4092c4;
color:#efefef;
}
#mytable td.active{
background:#106284;
color:#efefef;
}
#mytable td:hover{
background:#e0e0e0;
color:#FF004F;
}
<ul id="mytable">
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
#mytable {
background:#d0d0df;
cursor:pointer;
list-style:none;
padding-left:0;
}
#mytable li {
background:#4092c4;
color:#efefef;
display:inline-block;
margin:2px -2px 2px 2px;
padding:3px;
}
#mytable li:hover {
background:#e0e0e0;
color:#FF004F;
}
#mytable li.active {
background:#106284;
color:#efefef;
}
$(document).ready(function(){ //Performs the following code when the document is fully loaded
//Assigns a click event handler to list items in an element with ID "myTable"
$("#mytable li").click(function () {
//Remove the active class from list items in #mytable that were not clicked
$("#mytable li").not($(this)).removeClass("active");
//Add the active class to the clicked element.
$(this).addClass("active");
});
});