我有一个用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;
}
答案 0 :(得分:3)
更改此行:
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
答案 1 :(得分:3)
我建议您在选择行时将其添加到类中,并在CSS中设置样式,而不是通过编程方式更改背景颜色。这样,当您取消选择该行时,您只需删除预先添加的类,它将返回到其原始状态。请参见下面的示例。
10.0
9.2
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");
}
}
答案 2 :(得分:2)
这可能非常简单,您只需要使用toggleClass()方法即可从所选的tr标记行添加或删除样式。 这可以通过JQuery轻松完成。
尝试一下:https://www.w3schools.com/jquery/html_toggleclass.asp
祝你好运!