gpt4 book ai didi

css - 使用 CSS & SASS 选择唯一类的 child

转载 作者:太空宇宙 更新时间:2023-11-04 07:31:15 25 4
gpt4 key购买 nike

我正在使用 SASS 为“tbody”元素中的行创建边框,但在某些情况下我无法将其删除。

例如,

在第一个 'tbody' 元素中,tbody 有 2 个子级 compDetails-row。我正在那里创建一个边界。

但是,在第二个 tbody 元素中,如您所见,只有 1 个 child 属于 compDetails-row 类,我不希望边框是应用。因此,我尝试使用 only-of-type 选择器,但它似乎不起作用。

我该如何解决?

<!-- language: lang-css -->

.compDetails-row {
position: relative;
&:before {
content: '';
display: inline-block;
height: 100%;
border-left: 1px solid grey;
float: right;
position: absolute;
right: 20%;
}
&.compDetails-row:only-of-type {
&:before {
border: none;
}
}
}

<!-- language: lang-html -->

<tbody>
<tr class="compDetails-row">
<td>Row1 Column1</td>
<td>Row1 Column2</td>
<td>Row1 Column3</td>
</tr>
<tr class="compDetails-row">
<td>Row2 Column1</td>
<td>Row2 Column2</td>
<td>Row2 Column3</td>
</tr>
<tr>
<td>View Details</td>
</tr>
</tbody>
<tbody>
<tr class="compDetails-row">
<td>Row1 Column1</td>
<td>Row1 Column2</td>
<td>Row1 Column3</td>
</tr>
<tr>
<td>View Details</td>
</tr>
</tbody>

最佳答案

不幸的是 :first-of-type 从字面上只检查标签名称(在本例中为 tr),目前没有 :first-of-class 伪类。理想情况下,如果有多个 .compDetails-row,您将能够在运行时修改表标记,如果没有,最好的选择是一些 JavaScript。

你可以访问 CSS/SASS,你不能访问 JavaScript 吗?这个问题仅针对 CSS 进行了标记,但正如我所提到的,如果不更改您的标记,它实际上是不可行的。

假设您能够访问 JavaScript 文件,或将 JavaScript 标记添加到网站的页脚,这里有一个简单的纯/普通 JavaScript 方法,将类 multiple 添加到.compDetails-row 如果在同一个 tbody 中有多个。

// Grab all the `<tbody>` elements in the document as an array
var tbodies = document.querySelectorAll('tbody');

// Loop through the `<tbody>`'s we grabbed
for( i = 0; i < tbodies.length; i++ ){

// Grab all the `.compDetails-row` elements that exist in the current <tbody>
rows = tbodies[i].querySelectorAll('.compDetails-row');

// If there's more than one `.compDetails-row`
if( rows.length > 1 ){

// Loop through the `.compDetails-row` elements
rows.forEach(function(item){

// Add the `multiple` class to them
item.classList.add('multiple');

});
}
}
.compDetails-row {
position: relative;
}

.compDetails-row.multiple:before {
content: '';
display: inline-block;
height: 100%;
border-left: 1px solid grey;
float: right;
position: absolute;
right: 20%;
}
<table>
<thead>
</thead>
<tbody>
<tr class="compDetails-row">
<td>Row1 Column1</td>
<td>Row1 Column2</td>
<td>Row1 Column3</td>
</tr>
<tr class="compDetails-row">
<td>Row2 Column1</td>
<td>Row2 Column2</td>
<td>Row2 Column3</td>
</tr>
<tr>
<td>View Details</td>
</tr>
</tbody>
<tbody>
<tr class="compDetails-row">
<td>Row1 Column1</td>
<td>Row1 Column2</td>
<td>Row1 Column3</td>
</tr>
<tr>
<td>View Details</td>
</tr>
</tbody>
</table>

关于css - 使用 CSS & SASS 选择唯一类的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49376742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com