问题
I have many table, want to set css style on first row of the table on case first row has rowspan.
<table>
<tbody>
<tr>
<td rowspan="2" width="110">Name</td>
<td width="110">Size</td>
<td width="110">Status</td>
</tr>
<tr>
<td>Meter</td>
<td>true/false</td>
</tr>
<tr>
<td>Code A</td>
<td>1</td>
<td>false</td>
</tr>
</tbody>
</table>
With this style I tried to change first row:
thead tr:first-child,
tbody tr:first-child {
background-color: #1DA6C0;color: #fff;
}
So I looking for a css style to change table just like Image:
回答1:
You can set it in Javascript background using:
nth-child(-n+${rowspan})
Eg.
let tr = document.getElementsByTagName("tr")[0];
let td = tr.getElementsByTagName("td")[0];
let rowspan = td.rowSpan? td.rowSpan:1;
var nodes = document.querySelectorAll(`tbody tr:nth-child(-n+${rowspan})`);
for (let i = 0; i < nodes.length; i++) {
nodes[i].style.background = '#1DA6C0';
}
https://jsfiddle.net/xugL8s9b/10/
回答2:
I don't think this is possible with CSS. You have to dynamically add the styles to the cells depending on the row-span. Here I am assuming that you can have row-span only on the 1st cell of tbody.
<script>
$(function () {
$("#mytable tr:nth-child(1) td:nth-child(1)").each(function () {
let rowspan = this.getAttribute("rowspan")
var css = `tbody tr:nth-child(-n+${rowspan}) {background-color: #1DA6C0;color: #fff;}`,
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
head.appendChild(style);
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
}
else {
style.appendChild(document.createTextNode(css));
}
});
});
</script>
来源:https://stackoverflow.com/questions/61783573/set-css-style-on-first-row-of-the-table-on-case-first-row-has-rowspan