4

我从外部源获取 HTML 并且无法更改代码,因此为了获得我们需要的结果,我需要有条件地隐藏内容。

在此示例中,我需要display:none在 h2 上设置 level-0 和 level-1(在本例中为财务)。

<section class="level-0">
<h2 id="4001567002">Finance</h2>
<section class="child level-1">
    <h2 id="4008036002">Fusion</h2>
        <div class="opening" department_id="4001567002,4008036002" office_id="4000758002" data-office-4000758002="true" data-department-4001567002="true" data-department-4008036002="true">
        <a data-mapped="true" target="_top" href="google.com">Business Systems Executive</a>
        <br>
        <span class="location">Sydney</span>
    </div>
</section>

可能没有 level-1 在这种情况下 level-0 标头应该可见:

<section class="level-0">
<h2 id="4008036002">Fusion</h2>
    <div class="opening" department_id="4001567002,4008036002" office_id="4000758002" data-office-4000758002="true" data-department-4001567002="true" data-department-4008036002="true">
    <a data-mapped="true" target="_top" href="google.com">Business Systems Executive</a>
    <br>
    <span class="location">Sydney</span>
</div>

id 是不可预测的,所以我不能基于此隐藏级别。

这在纯 CSS 中是否可行,还是我应该想出另一个解决方案?

4

1 回答 1

1

我不能用纯 CSS 做你想做的事,我认为这是不可能的,因为你不能在 CSS 中添加条件语句。

请在下面找到一个带有一点 jquery 的解决方案:

var count = $(".level-0").length +1;

for (i = 1; i < count; i++) { 
  if ($(".level-1").parents('.container > .level-0:nth-of-type(' + i + ')').length == 1) {
    $( '.level-0:nth-of-type(' + i + ')').addClass( "has-lv1" );
  } else {
    $( '.level-0:nth-of-type(' + i + ')').addClass( "no-lv1" );
  }
}
.container {
  border: solid 1px black;
  padding: 20px;
  background-color: lightblue;
}

.container > h2{
  color: green;
}

.has-lv1 > h2 {
  display: none;
}

.no-lv1 > h2 {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h2>Example with <strong>Level 1</strong></h2>
  <section class="level-0">
    <h2 id="4001567002">Finance</h2>
    <section class="child level-1">
      <h2 id="4008036002">Fusion</h2>
      <div class="opening" department_id="4001567002,4008036002" office_id="4000758002" data-office-4000758002="true" data-department-4001567002="true" data-department-4008036002="true">
        <a data-mapped="true" target="_top" href="google.com">Business Systems Executive</a>
        <br>
        <span class="location">Sydney</span>
      </div>
    </section>
  </section>
<hr>
<h2>Example without <strong>Level 1</strong></h2>
  <section class="level-0">
    <h2 id="4001567002">Finance</h2>
  </section>
</div>

我希望这有帮助

于 2018-06-14T10:14:57.337 回答