我有一个用PHP构建的表格,样式是偶数行灰色和奇数行白色。行可以被选中和取消选中,当一行被选中时,它会变成蓝色,现在当我取消选中它时,我希望它回到原始样式,(现在我只设法将行变成灰色,但原始样式是只有偶数行是灰色的)
函数选择和取消选择行:获取一行,如果行是蓝色的(例如,行被选中)它变成灰色,否则:它变成蓝色(例如选择它)
<script>
var selected_sqf =0 ;
var selected_weight=0 ;
function myFunction(row,w) {
if(String(row.style.backgroundColor)=="rgb(30, 144, 255)")
{row.style.backgroundColor='#dddddd';
selected_sqf -= parseFloat((row.cells[10].innerHTML));
selected_weight -=parseFloat((row.cells[11].innerHTML));;
document.getElementById("selected_sqf").innerHTML = selected_sqf;
document.getElementById("selected_weight").innerHTML = selected_weight;
}
else {
row.style.backgroundColor='#1E90FF';
selected_sqf += parseFloat((row.cells[10].innerHTML));
selected_weight +=parseFloat((row.cells[11].innerHTML));;
document.getElementById("selected_sqf").innerHTML = selected_sqf;
document.getElementById("selected_weight").innerHTML = selected_weight;
//alert(row.style.backgroundColor)
}
}
</script>Stlye:
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 67%;
}
table, th, td {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}发布于 2019-01-01 16:40:33
我建议你在选择它的时候添加一个类到行中,并在css中设置样式,而不是通过编程改变背景颜色。这样,当您取消选择行时,您只需删除预先添加的类,它将返回到其原始状态。请参见下面的示例。
document.querySelector('#mytable').onclick = function(ev) {
var row = ev.target.parentElement;
if (row.classList.contains("blueel")) {
row.classList.remove("blueel");
} else {
row.classList.add("blueel");
}
}table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 67%;
}
table, th, td {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
tr.blueel {
background-color: blue;
}<table id="mytable">
<tr>
<th>title 1</th><th>title 2</th><th>title 3</th>
</tr>
<tr>
<td>element</td><td>element</td><td>element</td>
</tr>
<tr>
<td>element</td><td>element</td><td>element</td>
</tr>
<tr>
<td>element</td><td>element</td><td>element</td>
</tr>
<tr>
<td>element</td><td>element</td><td>element</td>
</tr>
</table>
发布于 2019-01-01 16:30:58
更改此行:
if(String(row.style.backgroundColor)=="rgb(30, 144, 255)")到这一行:
if (row.getPropertyValue("background-color") =="rgb(30, 144, 255)")window.getComputedStyle是一个函数,它接受一个元素作为参数,并返回一个对象,其中包含在该对象上使用的所有样式。然后,我们可以在结果上调用getPropertyValue来获取css属性的值。
阅读更多:https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
发布于 2019-01-01 16:57:20
它可以非常简单,您只需要使用toggleClass()方法来添加或删除您选择的tr标记行中的样式。这可以通过JQuery很容易地完成。
试试这个:https://www.w3schools.com/jquery/html_toggleclass.asp
祝你好运!
https://stackoverflow.com/questions/53994010
复制相似问题