首页 > 解决方案 > 有没有办法递归地选择一个班级的所有孩子到另一个班级

问题描述

例如在代码中

<div class="ofChildClass">
  <div class="other1">
    <div class="other2">
      <div class="ofStopClass">
        <div class="other3">
          <div class="other4">Text</div>
        </div>
      </div>
    </div>
    <div class="other5"></div>
    <div class="ofStopClass"></div>
    </div>
  </div>
</div>

我想选择的元素标记为选中,我不想选择的元素标记为未选中。

<div class="ofChildClass" unselected>
  <div class="other1" selected>
    <div class="other2" selected>
      <div class="ofStopClass" unselected>
        <div class="other3" unselected>
          <div class="other4" unselected>Text</div>
        </div>
      </div>
    </div>
    <div class="other5" selected></div>
    <div class="ofStopClass" unselected></div>
    </div>
  </div>
</div>

是否可以制作一个或多个选择器来选择这些元素而无需蛮力。

将问题放入代码中是否有可能做到这一点

.ofChildClass > :not(.ofStopClass),
.ofChildClass > :not(.ofStopClass) > :not(.ofStopClass),
.ofChildClass > :not(.ofStopClass) > :not(.ofStopClass) > :not(.ofStopClass),
.ofChildClass > :not(.ofStopClass) > :not(.ofStopClass) > :not(.ofStopClass) > :not(.ofStopClass)
...

无需重复。

标签: htmlcsscss-selectors

解决方案


不确定您要应用哪种 CSS,但可以使用 CSS 变量定义此行为,如下所示:

:root {
  --c:initial; /* we start by initial (nothing defined, default value)*/
}

div {
  outline:4px solid;
  outline-color:var(--c);
  padding:10px;
  margin:5px;
}
div::before {
  content:attr(class);
}

/* we define the color here */
.ofChildClass > * {
  --c:red;
}

/* we reset the coloration again here*/
.ofStopClass {
  --c:initial;
}
<div class="ofChildClass">
  <div class="other1">
    <div class="other2">
      <div class="ofStopClass">
        <div class="other3">
          <div class="other4">Text</div>
        </div>
      </div>
    </div>
    <div class="other5"></div>
    <div class="ofStopClass"></div>
  </div>
</div>


推荐阅读