如果元素为空,则使用 JS 删除 css 类

卢西奥·布拉卡蒙特斯

我有多个表格在整个文档中保存图像。每个表有 3 行(标题/图像/来源)。我需要使用 CSS 为我的标题设置样式以具有边框,但是当标题为空白时,标题类仍会出现在我的标记中,从而导致出现随机边框。

带标题的表格:

<table class="img-include">
  <tr>
    <td class="caption">My Caption </td>
  </tr>
  <tr>
    <td class="image"><img src="..." /></td>
  </tr>
  <tr>
    <td class="source">My Source</td>
  </tr>
</table>

没有标题的表格,class="caption" 仍然在表格单元格中:

<table class="img-include">
  <tr>
    <td class="caption"></td>
  </tr>
  <tr>
    <td class="img"><img src="..." /></td>
  </tr>
  <tr>
    <td class="source">My Source</td>
  </tr>
</table>

我想删除空单元格的标题类,但我当前的 JS 删除了我所有元素的类:

//remove empty caption
if ($('.caption').is(':empty')){
  $("td").removeClass( ".caption" );
}

我如何更新它,以便它只删除空 .caption 单元格的类

JS小提琴:https : //jsfiddle.net/5dq63zL4/

或德罗里

您可以使用:empty带有:not,的 CSS 伪类来设置非空标题的样式,而不是使用 JS 删除类

table {
  margin: 20px 0
}

.caption:not(:empty) {
  border-bottom: 1px solid red;
}

.source {
  font-size: .85em;
  color: #777
}
<table class="img-include">
  <tr>
    <td class="caption">My Caption </td>
  </tr>
  <tr>
    <td class="image"><img src="https://via.placeholder.com/350x150" /></td>
  </tr>
  <tr>
    <td class="source">My Source</td>
  </tr>
</table>


<table class="img-include">
  <tr>
    <td class="caption"></td>
  </tr>
  <tr>
    <td class="image"><img src="https://via.placeholder.com/350x150" /></td>
  </tr>
  <tr>
    <td class="source">My Source</td>
  </tr>
</table>


<table class="img-include">
  <tr>
    <td class="caption">My Caption </td>
  </tr>
  <tr>
    <td class="image"><img src="https://via.placeholder.com/350x150" /></td>
  </tr>
  <tr>
    <td class="source">My Source</td>
  </tr>
</table>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章