我知道 :nth-child 实际上是在检查“子项”与“可见子项”,但是是否有一个选择器可以处理可见子项?
假设我有一个表格,我将奇数行设置为不同的颜色
我有一个搜索过滤器,可以隐藏与搜索不匹配的行。现在,当我搜索时,行不再交替颜色。
当然,我可以向每个元素添加/删除类,我基本上已经这样做来隐藏/显示它们,但我想我会问是否有 CSS 方法可以做到这一点。
const searchElem = document.querySelector('input');
const tableElem = document.querySelector('table');
function search() {
const str = searchElem.value.toLowerCase();
const rows = tableElem.querySelectorAll('tr');
rows.forEach(function(row){
const text = row.textContent.toLowerCase();
if (str.length && !text.includes(str)) {
row.classList.add('hide');
} else {
row.classList.remove('hide');
}
});
}
searchElem.addEventListener('keyup', search);
tr {
background-color: #CDF;
}
tbody>tr:nth-child(odd) {
background-color: #DEF;
}
thead>tr {
background-color: lightgreen;
}
.hide {
display: none;
}
| Name | Amount |
| Apple | 220 |
| Watermelon | 465 |
| Orange | 94 |
| Pear | 567 |
| Cherry | 483 |
| Strawberry | 246 |
| Nectarine | 558 |
| Grape | 535 |
| Mango | 450 |
| Blueberry | 911 |
| Pomegranate | 386 |
| Carambola | 351 |
| Plum | 607 |
| Banana | 292 |
| Raspberry | 912 |
| Mandarin | 456 |
| Jackfruit | 976 |
| Papaya | 200 |
| Kiwi | 217 |
| Pineapple | 710 |
| Lime | 983 |
| Lemon | 960 |
| Apricot | 647 |
| Grapefruit | 861 |
| Melon | 226 |
| Coconut | 868 |
| Avocado | 385 |
| Peach | 419 |
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
没有选择器,但如果您愿意接受这种情况的特定解决方案,那么您可以依赖如下所示的渐变:
const searchElem = document.querySelector('input'); const tableElem = document.querySelector('table'); function search() { const str = searchElem.value.toLowerCase(); const rows = tableElem.querySelectorAll('tr'); rows.forEach(function(row){ const text = row.textContent.toLowerCase(); if (str.length && !text.includes(str)) { row.classList.add('hide'); } else { row.classList.remove('hide'); } }); } searchElem.addEventListener('keyup', search);thead>tr { background-color: lightgreen; } .hide { display: none; } table { position:relative; /* relative to all the table */ z-index: 0; } td { line-height: 1.2em; /* the height */ clip-path: inset(0); /* clip the pseudo element to td */ } tbody td:before { content: ""; position: absolute; z-index: -1; inset: 0; background: repeating-linear-gradient( #CDF 0 calc(1.2em + 4px), /* height + 2*border-spacing */ #DEF 0 calc(2.4em + 8px) /* 2*height + 4*border-spacing */ ); }