我从外部源获取
HTML并且无法更改代码,因此为了获得我们需要的结果,我需要有条件地隐藏内容.
在这个例子中,我有一个0级和1级,我需要在h2上设置display:none(在这种情况下是财务).
<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中是可能的还是我应该提出另一种解决方案?
最佳答案 我无法用Pure 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>
我希望这有帮助