首页 > 解决方案 > 在最后一次出现类之后和使用 CSS 的特定类之前选择元素

问题描述

我试图在不使用 JavaScript 循环的情况下解决问题。我想将 css 规则应用于表格单元格。我在开始单元格之前很难应用规则。

我发现这个问题Select all elements before element with class? 我很难实现这种技术,因为我的代码需要更复杂的检查。尤其是考虑在开始前处理两个预订时。

如果我能在开始前找到最后一个预订,我可以使用该问题中的技术。

有谁知道如何在没有 javascript 的情况下解决这个问题?

table {
  margin: auto;
  width: 100%;
  border: thick groove black;
  border-radius: 5px;
  text-align: center;
}
td {
  border: thin groove gray;
  width: 10vw;
  height: 5vh;
}
td:hover {
  cursor: pointer;
}
td.start {
  background-color: green;
}
td.booked {
  background-color: orange;
  cursor: not-allowed;
}
td.start ~ td:not(.booked) {
  background-color: lightblue;
}
td.start ~ td ~ td.booked:hover {
  cursor: not-allowed;
}
td.start ~ td ~ td.booked ~ td {
  background-color: red;
}
td.start ~ td ~ td.booked ~ td:hover {
  cursor: not-allowed;
}
<br />
<table>
  <thead>
    <tr>
      <td>Invalid</td>
      <td>Invalid</td>
      <td>Booked</td>
      <td>OK</td>
      <td>OK</td>
      <td>Start</td>
      <td>OK</td>
      <td>OK</td>
      <td>Booked</td>
      <td>Invalid</td>
      <td>Invalid</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td></td>
      <td class="booked"></td>
      <td></td>
      <td></td>
      <td class="start"></td>
      <td></td>
      <td></td>
      <td class="booked"></td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>

<p
  style="text-align:center; border: thin groove gray; border-radius:5px; margin: 1.25rem 4vw;
          padding: 1.25rem; 
          "
>
  Relative to th start cell, cells after a booking are not allowed. Cells before a booking are allowed.
  <br />
  <br />

  We can select the cells after the start cell with: <br /><br />
  <code
    style="background-color:lightgray; padding:.75rem;
               border-radius: 5px
               "
    >td.start ~ td:not(.booked) { background-color: lightblue; }</code
  >
  <br />
  <br />

  We can select the cells after the booked cell after the start cell with:
  <br /><br />
  <code
    style="background-color:lightgray; padding:.75rem;
               border-radius: 5px
               "
    >td.start ~ td ~ td.booked ~ td { background-color: red; }</code
  >
  <br />
  <br />
  <br />
  <strong>
    Q. How can we select the cells before the start cell and apply the rules ?</strong
  >
  <br />
</p>

标签: htmlcss

解决方案


在这种情况下,我认为无法通过链接问题的下一个兄弟组合器和通用选择器组合来实现。使用 JavaScript 或 apply class,为data-*每个td元素添加属性。


推荐阅读