html - 有没有办法递归地选择一个类(class)的所有 child 到另一个类(class)

标签 html css css-selectors

例如在代码中

<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)
...

无需重复。

最佳答案

不确定您要应用哪种 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>

关于html - 有没有办法递归地选择一个类(class)的所有 child 到另一个类(class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62617389/

相关文章:

html - 多列,列跨度解决方法

javascript - 改变颜色选择器不改变 Canvas 背景颜色

css - 哪些字符在 CSS 类名/选择器中有效?

jQuery nth-child 选择器不起作用

html - 垂直对齐需要水平扩展的 <li> 内的链接内的文本

javascript - 如何从 JavaScript 文件中的 JSON 文件访问数据,然后将其打印到 HTML 页面?

javascript - 启用严格的 MIME 类型检查,拒绝从 '<url>' 执行脚本它的 MIME 类型 ('text/plain')不可执行,并且

html - 具有动态高度的垂直滚动 div

javascript - jQuery 旋转函数 - 在图像点击时指定 20% 旋转?

javascript - CSS/XPATH 选择器查询