如何在一个嵌套复选框 and change element in another upon :checked? [duplicate]

问题描述 投票:0回答:1

当我将我的复选框嵌套在<div>元素中时,我的代码停止工作。我需要在检查某个复选框时显示图像。代码无需将复选框嵌套在<div>中。

我希望我的复选框嵌套在<div>中,以便在选择某个复选框时,将<div>中的显示值从none更改为inline-block。

我已经尝试了一切,但我想我无法理解这个问题。

<body>

<style>
  input[type=checkbox]:checked.ivo ~ div #fotoivo {
    display: inline-block;
 }

input[type=checkbox]:checked.ian ~ div #fotoian {
    display: inline-block;
 }

input[type=checkbox]:checked.non ~ div #fotonon {
    display: inline-block;
 }

#fotoivo {
    width: 200px;
    display: none;
}

#fotoian {
    width: 200px;
    display: none;
}

#fotonon {
    width: 200px;
    display: none;
}
</style>

<!--Checkboxes (works without the <div> wrapped around)-->
<!--<div>-->
  Ivo: <input type="checkbox" name="ivoian" class="ivo">
  Ian: <input type="checkbox" name="ivoian" class="ian">
  Non-binair: <input type="checkbox" name="ivoian" class="non">
<!--</div>-->

<!--Images that should change from display: none to inline-block.-->
  <div>
    <img id="fotoivo" src="ivo.jpg" alt="#">

    <img id="fotoian" src="ian.jpg" alt="#">

    <img id="fotonon" src="non.jpg" alt="#">
  </div>

</body>
html css checkbox
1个回答
0
投票

蒂尔达(~)是兄弟选择者。当您嵌套输入时,div包装图像不再是他们的兄弟姐妹了。由于CSS没有父选择器,因此您无法仅使用css。但是,当然,你可以用简单的JS做到这一点。

你可以这样做:https://stackoverflow.com/a/7691692/11404579

编辑:此外,只有CSS有一些hacky方式,但你将失去本机输入。您可以将输入放在根元素中,这样您就可以选择带有兄弟选择器的图像并隐藏输入。并在一些嵌套元素中放置那些隐藏输入的标签。这样,当您单击(嵌套)标签时,您检查输入a可以控制内容。

© www.soinside.com 2019 - 2024. All rights reserved.