我绝对不会鼓励您使用 JavaScript 进行样式设置。相反,尽可能多地使用 CSS 以保持高性能和低脚本依赖性。
我假设您的表结构如下所示。我尽力从您的屏幕截图中重新创建:
<table data-start-day="sun">
<thead>
<tr>
<th>Year</th>
</tr>
<tr>
<th rowspan="2">Month</th>
<th>1</th><!-- fill in --><th>31</th>
</tr>
<tr>
<th>S</th><th>M</th><!-- fill in -->
</tr>
</thead>
<tbody>
<tr>
<td>Employee</td>
<td></td><!-- x days in month -->
</tr>
<tr>
<td>Exceptions</td>
<td></td><!-- x days in month -->
</tr>
</tbody>
</table>
接下来,我们将使用IE 9 及更高版本支持的一系列复合选择器。请注意,主要功能是通过使用:nth-of-type
,我们可以使用它来定位 Sat/Sun 列,无论它们位于日历本身的哪个位置:
table[data-start-day=sat] thead tr:last-child th:nth-of-type(7n-13),
table[data-start-day=sat] thead tr:last-child th:nth-of-type(7n-12),
table[data-start-day=sat] tbody tr:nth-of-type(2n) :nth-of-type(7n-12):not(:first-child),
table[data-start-day=sat] tbody tr:nth-of-type(2n) :nth-of-type(7n-11):not(:first-child),
table[data-start-day=fri] thead tr:last-child th:nth-of-type(7n-12),
table[data-start-day=fri] thead tr:last-child th:nth-of-type(7n-11),
table[data-start-day=fri] tbody tr:nth-of-type(2n) :nth-of-type(7n-11):not(:first-child),
table[data-start-day=fri] tbody tr:nth-of-type(2n) :nth-of-type(7n-10):not(:first-child),
table[data-start-day=thu] thead tr:last-child th:nth-of-type(7n-11),
table[data-start-day=thu] thead tr:last-child th:nth-of-type(7n-10),
table[data-start-day=thu] tbody tr:nth-of-type(2n) :nth-of-type(7n-10):not(:first-child),
table[data-start-day=thu] tbody tr:nth-of-type(2n) :nth-of-type(7n-9):not(:first-child),
table[data-start-day=wed] thead tr:last-child th:nth-of-type(7n-10),
table[data-start-day=wed] thead tr:last-child th:nth-of-type(7n-9),
table[data-start-day=wed] tbody tr:nth-of-type(2n) :nth-of-type(7n-9):not(:first-child),
table[data-start-day=wed] tbody tr:nth-of-type(2n) :nth-of-type(7n-8):not(:first-child),
table[data-start-day=tue] thead tr:last-child th:nth-of-type(7n-9),
table[data-start-day=tue] thead tr:last-child th:nth-of-type(7n-8),
table[data-start-day=tue] tbody tr:nth-of-type(2n) :nth-of-type(7n-8):not(:first-child),
table[data-start-day=tue] tbody tr:nth-of-type(2n) :nth-of-type(7n-7):not(:first-child),
table[data-start-day=mon] thead tr:last-child th:nth-of-type(7n-8),
table[data-start-day=mon] thead tr:last-child th:nth-of-type(7n-7),
table[data-start-day=mon] tbody tr:nth-of-type(2n) :nth-of-type(7n-7):not(:first-child),
table[data-start-day=mon] tbody tr:nth-of-type(2n) :nth-of-type(7n-6):not(:first-child),
table[data-start-day=sun] thead tr:last-child th:nth-of-type(7n-7),
table[data-start-day=sun] thead tr:last-child th:nth-of-type(7n-6),
table[data-start-day=sun] tbody tr:nth-of-type(2n) :nth-of-type(7n-6):not(:first-child),
table[data-start-day=sun] tbody tr:nth-of-type(2n) :nth-of-type(7n-5):not(:first-child){
background:#CCC;
}
结果与您想要的输出相匹配:
小提琴:http: //jsfiddle.net/80fajvd6/4/