gpt4 book ai didi

css - 有条件地根据其他类的存在隐藏元素

转载 作者:行者123 更新时间:2023-11-28 08:50:13 25 4
gpt4 key购买 nike

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

在这个例子中,我有 level-0 和 level-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 中是否可行,还是我应该想出另一种解决方案?

最佳答案

我不能用纯 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>

希望对你有帮助

关于css - 有条件地根据其他类的存在隐藏元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50851713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com