检查元素是否存在,然后应用 css

Check if element exists, then apply css

我的HTML代码基本上是

<div class="a">
  <div class="b">
    ...
  </div>
</div>
<div class="c">
  ...
</div>

我现在想将 display: none; 应用于 c,但前提是 b 存在。 a 和 c 总是存在的。

我的方法是

.a .b ~ .c {
  display: none;
}

这应该适合你:

var b = document.querySelector('.b');

if (b) {
  document.querySelector('.c').style.display = 'none';
}
<div class="a">a
  <div class="b">b</div>
</div>

<div class="c">c</div>

显然,JavaScript 是必需的,但只需轻轻一点。您可以将 document.querySelector('.b) 添加到 if 语句,而不是将其也保存到变量中。

编辑:稍微澄清一下您的代码有什么问题 - 您是第一个 selecting .a .b,它将 select b class 如果它是 a class 的后代,那么你正在使用通用兄弟组合器(后续兄弟组合器),但它不会select c class。这是因为 c class 在 a 元素之外,因此不是 a class 的后代。一个纯粹的 CSS 解决方案是将 c class 放在 a 元素中,这将使您当前的 CSS 工作并且 JavaScript不需要。例如,您的 HTML 将如下所示:

.a .b ~ .c {
   display: none;
}
<div class="a">a
    <div class="b">b</div>
    <div class="c">c</div>
</div>

在旁注中,general sibling combinator ~ operator will look for any subsequent element that comes after b with a class of c. If you only wanted to apply it to the first element with a class of c that comes after b, consider using the adjacent sibling selector +,也称为 'next-sibling combinator'。